Skip to content

Instantly share code, notes, and snippets.

@daiplusplus
Last active November 25, 2021 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daiplusplus/44ad0b59e27f14e15061b332053c1c9e to your computer and use it in GitHub Desktop.
Save daiplusplus/44ad0b59e27f14e15061b332053c1c9e to your computer and use it in GitHub Desktop.
System.Type's properties comparison for different kinds of generics
// This LinqPad 6 script is for https://stackoverflow.com/a/70111165/159145
<Query Kind="Program">
<IncludePredicateBuilder>false</IncludePredicateBuilder>
<UseNoncollectibleLoadContext>true</UseNoncollectibleLoadContext>
</Query>
class NormalClass { }
class Generic<T> { }
class Derived : Generic<String> { }
class HasGenericMethod { public void Foo<T>() {} }
void Main()
{
Type openGeneric = typeof(Generic<>);
Type genTypeArg = openGeneric.GetGenericArguments().Single();
Type genMethodArg = typeof(HasGenericMethod).GetMethod( nameof(HasGenericMethod.Foo) )!.GetGenericArguments().Single();
Type[] types = new Type[]
{
typeof(NormalClass ),
openGeneric,
typeof(Generic<String>),
typeof(Derived ),
genTypeArg,
genMethodArg,
typeof(Generic<String>[])
};
var withMethodsResults = types
.Select( t => new
{
_0_Type = t,
_1_IsTypeDefinition = t.IsTypeDefinition,
_2_IsGenericType = t.IsGenericType,
_3_ContainsGenericParameters = t.ContainsGenericParameters,
_4_GenericTypeArguments = t.GenericTypeArguments,
_5_IsConstructedGenericType = t.IsConstructedGenericType,
_6_IsGenericTypeDefinition = t.IsGenericTypeDefinition,
_7_IsGenericParameter = t.IsGenericParameter,
_8_IsGenericMethodParameter = t.IsGenericMethodParameter,
_9_IsGenericTypeParameter = t.IsGenericTypeParameter,
GetGenericArguments = TryDo( t, t2 => t2.GetGenericArguments() ),
GetGenericParameterConstraints = TryDo( t, t2 => t2.GetGenericParameterConstraints() ),
GetGenericTypeDefinition = TryDo( t, t2 => t2.GetGenericTypeDefinition() )
} )
.ToList();
withMethodsResults.Dump( alpha: true );
}
public static Object? TryDo<TSource,TResult>( TSource src, Func<TSource,TResult> getter )//, TResult defaultValue )
{
try
{
TResult result = getter( src );
return result;
}
catch( Exception ex )
{
return ex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment