I've been baffled by this and can't seem to get my head around it so hopefully someone can point me in the right direction.
I have a class as follows:
public class Foo<T>
{
public List<T> Data;
}
Now I'm writing code to reflect this class and want to work out a way of determining that the field Data has a generic parameter being used.
My initial approach was to continue going down as many levels as I could and once I hit the IsGenericParameter field set to true I would rather than reflect the type name instead place a "Generic Argument" string there, however I can't seem to get this to work the way I want it to.
I've looked around but every solution I've found seems to point to a dead end with this at the moment.
You want IsGenericType, not IsGenericParameter:
bool isGeneric = typeof(Foo<int>).GetField("Data").FieldType.IsGenericType;
If you want to know of the parameter for the List is generic, then you have to look one more level down:
bool isGeneric = typeof(Foo<>).GetField("Data")
.FieldType
.GetGenericArguments()[0] // only generic argument to List<T>
.IsGenericParameter;
what if Data field was a Dictionary with Dictionary<string, T>. How would I determine which type was using a generic parameter?
Call GetGenericArguments on the type and look at each type in the resulting array
public class Foo<T>
{
public Dictionary<string, T> Bar;
}
Type[] types = typeof(Foo<>).GetField("Bar").FieldType.GetGenericArguments();
Console.WriteLine("{0}\n{1}",
types[0].IsGenericParameter, // false, type is string
types[1].IsGenericParameter // true, type is T
);
Basically, IsGenericParameter is used when looking at the generic parameters of a type to see if it is generic or if is has a type sepcified.
Here is how to distinguish generic types that rely on class type parameter from generic types that do not. Consider this example:
class Foo<T> {
public List<T> field1; // You want this field
public List<int> field2; // not this field
}
Start by getting generic type definition, and pulling its type arguments:
var g = typeof(Foo<string>).GetGenericTypeDefinition();
var a = g.GetGenericArguments();
This will give you an array with a single type that represents generic type parameter T. Now you can go through all fields, and search for that type among generic type arguments of field types, like this:
foreach (var f in g.GetFields()) {
var ft = f.FieldType;
if (!ft.IsGenericType) continue;
var da = ft.GetGenericArguments();
if (da.Any(xt => a.Contains(xt))) {
Console.WriteLine("Field {0} uses generic type parameter", f.Name);
} else {
Console.WriteLine("Field {0} does not use generic type parameter", f.Name);
}
}
This code produces the following output:
Field field1 uses generic type parameter
Field field2 does not use generic type parameter
Related
How to use the dynamic when specifying generic type arguments in C#?
I am reading the CLR via C# book. And I come across the following paragraph:
It is also possible to use dynamic when specifying generic type arguments to a generic class
(reference type), a structure (value type), an interface, a delegate, or a method. When you do this, the
compiler converts dynamic to Object and applies DynamicAttribute to the various pieces of
metadata where it makes sense. Note that the generic code that you are using has already been
compiled and will consider the type to be Object; no dynamic dispatch will be performed because the
compiler did not produce any payload code in the generic code.
As far as I understand this excerpt tells that I can use the dynamic as a type argument in (e.g.) a class definition. But after trying this out I come to a conclusion that it is no different from using any other placeholder in the type argument. So, I doubt that my understanding is correct.
using System;
namespace myprogram
{
class A<dynamic> {
public dynamic a;
}
class B {
public Int32 b;
}
class C<T> {
public T c;
}
class Program {
static void Main(string[] args) {
//Cannot implicitly convert type 'string' to 'myprogram.B' [Console.NET]csharp(CS0029)
//A<B> a = new A<B> {a = "foo"};
//Cannot implicitly convert type 'string' to 'myprogram.B' [Console.NET]csharp(CS0029)
//C<B> c = new C<B> {c = "foo"};
//as you can see it does not matter if I use the T or dynamic, the effect is the same
//so, what is the use of using the dynamic in the class definition?
}
}
}
It is very important to understand the difference between type "arguments" and type "parameters".
Consider this:
class Foo<T> { } // "T" is a type parameter
...
Foo<int> f; // "int" is a type argument
Type parameters declare what types you can pass to this generic type/method. Type parameters are essentially identifiers, not an existing type. When you pass a type to a generic type/method, the type you passed is called the type argument. This is quite similar to the difference between a method parameter and argument.
So the excerpt is trying to say that given a generic type, you can pass the type dynamic to it, and it will be treated as object by the CLR. It doesn't mean that you can do this:
class A<dynamic> {
}
It means that you can do this:
var list = new List<dynamic>();
Or with the types declared in your code:
C<dynamic> c = new C<dynamic> {c = "foo"};
Short answer: in your code dynamic is just a type parameter name, you're not actually passing an argument.
As far as I understand this excerpt tells that I can use the dynamic as a type argument in (e.g.) a class definition.
There are no type arguments in a class definition. In the definition of a generic type there are type parameters. When you construct a generic type these are type arguments. So this:
class A<dynamic>
{
}
var a = new A<string>();
is a generic type with one type parameter whose name is dynamic. Then follows an instantiation of the type where string is passed as a type argument to the type parameter dynamic. This:
class A<T>
{
}
var a = new A<dynamic>();
is a generic type with one type parameter whose name is T. Then follows an instantiation of the type where dynamic is passed as a type argument to the type parameter T.
You're looking for the latter, not the former.
You can use dynamic as an Argument, so you can use
var c = new C<dynamic>();
But you cannot use a concrete Type, to build a generic Type, like
class A<dynamic> { }
class B<int> { }
In underline: This you should NOT do ! You are defining an argument name here !
Actually it doesn't cause compile-error, but the word "int" as treated as a parameter name, same as there would be T. It's a good paradigm to use names starting with T for generic type parameters, not to mix it up, with any type from the Rest of your program.
As you concluded yourself, your definition of A and C are completly identical,
except you are confused, cause the word dynamic has nothing to do with the type
dynamic in this place.
If you want to assign a string, of course you have to create a new C<string>() or new C<object>() or any other type accepting a string.
In my case I was in reality masking an ExpandoObject as a dynamic, so I ended up using code like this:
static async Task<TReturn> GenericMethodAsync<TReturn()
{
if (typeof(TReturn) == typeof(ExpandoObject))
// Return an ExpandoObject
}
Which was then used by a method like this one
static async Task<dynamic> OtherMethodAsync()
{
return await GenericMethodAsync<ExpandoObject>();
}
I'm trying to reference the type of a property on a class and I can't figure out the syntax:
List<IChildInfo<typeof(MappingModel.identifier)>> mappings;
Is this possible in .NET?
public class MappingModel
{
public long identifier { get; set; }
}
The code you've presented won't work because the compiler has to create a specialized type for that particular list using the type you've specified.
The easiest way of fixing that would be to make a generic specialization "on the fly" ( or at run-time ).
example code:
// retrieve the property which type you want to get
var propertyInfo = typeof(MappingModel).GetProperty("identifier");
// get that property's type
Type propertyType = propertyInfo.PropertyType;
// now that you have a property type you can make a specialized generic type:
Type ichildtype = typeof(IChildInfo).MakeGenericType(propertyType);
// create a type definition for that particular list
Type listtype = typeof(List<>).MakeGenericType(ichildtype);
// create an instance of that list
Activator.CreateInstance(listtype);
Try this online
First examine the type of your surrounding class, then get its properties:
var p = typeof(MappingModel).GetProperties.FirstOrDefault(x => x.Name == "identifier");
Or also:
var p = typeof(MappingModel).GetProperty("identifier");
Now you can get the type of the property via PropertyType:
var t = p.PropertyType;
However as this is a runtime-information teherĀ“s no way for the compiler to create an instance of a list of that type. You can create an interface that your type implements and then create a list of it:
var l = new List<IChildInfo<MyInterface>>();
where the type of MappingModel.identifier implements MyInterface. But this assumes IChildInfo to be co-variant:
interface IChildInfo<out T> { ... }
You need to use Reflection to that.
I'm not sure of what exactly you want to do but you can get all the property of a class doing :
typeof(MappingModel).GetProperties();
Then you can play with the properties.
You can get the type of the property, but you won't be able to use it as a generic argument using normal syntax. You can use MethodInfo to invoke a method that would use mappings. This answer may prove to be helpful to you.
Say that I have a class like this:
public class TestClass <T>
{
public T Prop { get; set; }
}
I'm trying to identify that the property type is T, not the actual type that is passed e.g. int
In order to clarify it a bit more:
TestClass<int> tc=new TestClass<int>();
tc.GetType().GetProperty("prop").PropertyType.Name; //this returns int, but I need "T"
When you create a TestClass<int> instance, you have a reified generic type - the property is int, not T.
To get at the actual generic type, you can use GetGenericTypeDefinition:
var genericType = tc.GetType().GetGenericTypeDefinition();
var typeName = genericType.GetProperty("Prop").PropertyType.Name;
And if you want to distinguish between actual types and generic type arguments, you can use Type.IsGenericParameter:
genericType.GetProperty("Prop").PropertyType.IsGenericParameter // true
Note that if you are are using C# 6, and require the generic type argument's name within it's defining class, you can get away without using reflection at all:
var name = nameof(T); // "T"
If you need the the generic type argument's name outside of it's class, you will need to use reflection (see Luaan's answer.)
What is the difference between Type.IsGenericType and Type.IsGenericTypeDefinition ? Interestingly enough, MSDN's link for IsGenericTypeDefinition is broken.
Update:
IsGenericTypeDefinition MSDN's entry
After playing a bit with trying to retrieve all the DbSets defined in a given DbContext, I was lead to the following, which behavior I am trying to understand: filtering properties via IsGenericType returns the desired results, while with IsGenericTypeDefinition not (does not return any).
It's interesting that from this post I have the impression that the author did get his DbSets using IsGenericTypeDefinition, while I did not.
Follows a sample that illustrates the discussion:
private static void Main(string[] args)
{
A a = new A();
int propertyCount = a.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType).Count();
int propertyCount2 = a.GetType().GetProperties().Where(p => p.PropertyType.IsGenericTypeDefinition).Count();
Console.WriteLine("count1: {0} count2: {1}", propertyCount, propertyCount2);
}
// Output: count1: 1 count2: 0
public class A
{
public string aaa { get; set; }
public List<int> myList { get; set; }
}
IsGenericType tells you that this instance of System.Type represents a generic type with all its type parameters specified. For example, List<int> is a generic type.
IsGenericTypeDefinition, on the other hand, tells you that this instance of System.Type represents a definition from which generic types can be constructed by supplying type arguments for its type parameters. For example, List<> is a generic type definition.
You can get a generic type definition of a generic type by calling GetGenericTypeDefinition:
var listInt = typeof(List<int>);
var typeDef = listInt.GetGenericTypeDefinition(); // gives typeof(List<>)
You can make a generic type from a generic type definition by providing it with type arguments to MakeGenericType:
var listDef = typeof(List<>);
var listStr = listDef.MakeGenericType(typeof(string));
(This answer compares all of the generic-type-related properties of Type in a side-by-side table below, so if you're already familiar with .NET's generics and just want a reference then just scroll down to the table)
First, remember the difference between parameters and arguments, especially w.r.t. generic type parameters and generic type arguments (and also generic method type parameters and generic method type arguments):
A generic type parameter is the declared type "placeholder" in an "open" generic type.
For example, in class Generic<T0,T1> {}, the T0 and T1 symbols are the generic type parameters. Note that when simply given a generic class definition that's unused then there's no type arguments.
A generic type argument is the type-identifier specified for a generic type parameter by a consumer of a generic class.
For example, in Generic<String,Object> gen = new Generic<String,Object> then...
...the generic type argument for generic type parameter T0 is String.
...the generic type argument for generic type parameter T1 is Object.
However, generic type arguments don't need to be concrete types: they can be a generic type parameter from the consumer's context.
For example, in class Generic<TItem> { public Object Foo() { return new List<TItem>(); } }
...then (inside the Foo method) the class Generic<TItem>'s generic type parameter TItem is used as the generic type argument for List<T>'s generic type parameter T.
Yes, if you get confused by all that don't worry because that's normal.
Finally, generic method type parameters and generic method type arguments work the same way as generic type parameters and generic type arguments, respectively, except they're scoped to a single method:
For example, the class NotGenericClass in class NotGenericClass { void GenericMethod<T>() { } } does not have any generic type parameters, but its method GenericMethod<T>() does have a single generic method type parameter - and if GenericMethod is never ever actually called/used/invoked then GenericMethod will not have any generic method type arguments as those only exist at generic instantiation sites (i.e. at the point of generic instantiation).
Given these C# classes...
class NormalClass { }
class Generic<T> { }
class Derived : Generic<String> { }
class HasGenericMethod { public void Foo<T>() {} }
...and these Type instances from GetGenericArguments():
Type[] genericTypeArgs = typeof(Generic<>).GetGenericArguments();
Type genTypeArg = genericTypeArgs.Single();
Type[] genericMethodTypeArgs = typeof(HasGenericMethod).GetMethod( nameof(HasGenericMethod.Foo) ).GetGenericArguments();
Type genMethodArg = genericMethodTypeArgs.Single();
...then their typeof() expressions will have these properties:
Example
typeof(NormalClass)
typeof(Generic<>)
typeof(Generic<String>)
typeof(Derived)
genTypeArg
genMethodArg
typeof(Generic<String>[])
Type properties
Type.IsTypeDefinition
Yes
Yes
No
Yes
No
No
No
Type.IsGenericType
No
Yes
Yes
No
No
No
No5
Type.ContainsGenericParameters
No
Yes
No
No
Yes4
Yes4
No
Type.GenericTypeArguments
Empty
Empty
{ typeof(String) }
Empty
Empty
Empty
Empty
Type.IsConstructedGenericType
No
No
Yes
No
No
No
No
Type.IsGenericTypeDefinition
No
Yes
No
No
No
No
No
Generic parameter properties:
Type.IsGenericParameter
No
No
No
No
Yes
Yes
No
Type.IsGenericMethodParameter
No
No
No
No
No
Yes
No
Type.IsGenericTypeParameter
No
No
No
No
Yes
No
No
Methods:
Type.GetGenericArguments()
Empty
{ typeof(T) }
{ typeof(String) }
Empty
Empty
Empty
{ typeof(String) }
Type.GetGenericParameterConstraints()
Exception1
Exception1
Exception1
Exception1
Empty
Empty
Exception1
Type.GetGenericTypeDefinition()
Exception2
typeof(Generic<>)
typeof(Generic<>)
Exception2
Exception2
Exception2
Exception2
You can generate this table yourself (albiet, transposed) using this LinqPad script.
As a reminder to myself: if you have a Type object from Object.GetType() for an object that may be either a closed generic type (i.e. Object.GetType().IsConstructedGenericType == true), or is a non-generic type derived from that generic type, and you want to find out what, do this:
private static readonly Type _knownGenericType = typeof(Generic<>);
public static Boolean TryGetTypeArgsOfKnownGenericType( Object obj, [NotNullWhen(true)] out Type? actualArgType )
{
Type t = obj.GetType();
while( t != null )
{
if t.IsConstructedGenericType && t.GetGenericTypeDefinition() == _knownGenericType )
{
Type[] tArgs = t.GetGenericArguments();
actualArgType = tArgs.Single();
return true;
}
t = t.BaseType;
}
actualArgType = null;
return false;
}
So this code below will print "Sucess: T := System.String" twice:
if( TryGetTypeArgsOfKnownGenericType( new Derived(), out Type? tArg ) )
{
Console.WriteLine("Success: T := " + tArg.FullName);
}
if( TryGetTypeArgsOfKnownGenericType( new Generic<String>(), out Type? tArg ) )
{
Console.WriteLine("Success: T := " + tArg.FullName);
}
Footnotes:
InvalidOperationException: "Method may only be called on a Type for which Type.IsGenericParameter is true."
InvalidOperationException: "This operation is only valid on generic types."
typeof(T) is typeof(Generic<>).GetGenericArguments().Single()
It's surprising that typeof(T).ContainsGenericParameters == true when T is a generic type parameter without an argument set (i.e. T is undefined), so I'd have expected an InvalidOperationException to be thrown instead.
The documentation for ContainsGenericParameters seemingly justifies returning true (emphasis mine):
For convenience and to reduce the chance of error, the ContainsGenericParameters property provides a standard way to distinguish between closed constructed types, which can be instantiated, and open constructed types, which cannot. If the ContainsGenericParameters property returns true, the type cannot be instantiated.
Apparently using typeof(T[]) when T is a constructed generic type: the ContainsGenericParameters property is false but the GetGenericArguments() method returns a non-empty array of the type-arguments of T instead of the type-arguments of System.Array (which isn't actually a generic type).
For example:
typeof(Generic<String>[]).IsGenericType == false
typeof(Generic<String>[]).GetGenericArguments() == new[] { typeof(String) }
This is documented in the rightmost column of the above table.
And described in the documentation:
The ContainsGenericParameters property searches recursively for type parameters. For example, it returns true for an array whose elements are type A<T> even though the array is not itself generic. Contrast this with the behavior of the IsGenericType property, which returns false for arrays.
bool IsTypeAGenericList(Type listType)
{
typeof(IList<>).IsAssignableFrom(listType.GetGenericTypeDefinition())
}
returns false when given typeof(List<int>).
I assume this is because the two type parameters can be different, correct?
Actually, this works:
public static bool IsGenericList(Type type)
{
if (!type.IsGenericType)
return false;
var genericArguments = type.GetGenericArguments();
if (genericArguments.Length != 1)
return false;
var listType = typeof (IList<>).MakeGenericType(genericArguments);
return listType.IsAssignableFrom(type);
}
This really has to do with open constructed types.
When you say:
class List<T> : IList<T>
You're actually saying: my class is called List, it has one type parameter called T, and it implements the interface that is constructed from IList<> using the same T. So the T in the definition part and the T in the "implements" part both refer to the same type parameter -- you declare it before the colon, then you immediately reference it after the colon.
It gets confusing because IList<>'s type parameter is also called T -- but that is a different type parameter entirely. So let's re-declare our concrete class like this:
class List<U> : IList<U>
This is completely equivalent to the above, only now we can say "U" when we refer to the type parameter of List, and T when we refer to the one from IList. They're different types.
Now it gets easier to see why the generic type definition List<U> (which is what you mean when you say typeof(List<>)) does not implement the generifc type definition IList<T> (which is what you mean when you say typeof(IList<>)), but rather it implements the open generic constructed type IList<U> (that is, IList constructed with List's own type paremeter).
So basically, generic type definitions never inherit or implement other generic type definitions -- they usually implement open constructed types using their own type parameters with other generic type definitions.
Ripper234's answer shows how to handle this particular case using Reflection, so I won't repeat it; I just wanted to clarify the relationship between those types, and I hope it came out at least somewhat intelligible.
I guess the method doesn't really make sense, because an instance is never of the generic type - it's always constructed with a particular type argument.
In other words, you could never have an "open" variable to assign into, nor a reference to an open instance to use as the value for the assignment.
As you say, you don't know whether the type parameters will be the same - so (for instance) you could define:
class BizarreList<T> : IList<int>
It feels like there should be some way of expressing the relationship though...
Here's the extension method from AutoMapper:
public static bool IsCollectionType(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ICollection<>))
{
return true;
}
IEnumerable<Type> genericInterfaces = type.GetInterfaces().Where(t => t.IsGenericType);
IEnumerable<Type> baseDefinitions = genericInterfaces.Select(t => t.GetGenericTypeDefinition());
var isCollectionType = baseDefinitions.Any(t => t == typeof(ICollection<>));
return isCollectionType;
}