Reputation: 552
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"
Upvotes: 1
Views: 1328
Reputation: 3212
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.)
Upvotes: 3
Reputation: 63722
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
Upvotes: 5