Reputation: 4386
I want to get the name of a class dynamically. I can use this:
public void RequestData<TResult>()
{
var myName = typeof(TResult).Name;
}
Which works fine e.g. if TResult
is of type MyClass
then myName
would equal "MyClass"
But if TResult is of type
List<MyClass>
I still want myName to equal "MyClass" ... at the moment it will be "List`1"
So if TResult
is going to be of type List
how can I programmatically know that it's a List
and then pick out the name of the type of this list?
Upvotes: 1
Views: 302
Reputation: 144136
You can get the 'leftmost' inner generic type with
public static Type GetInnermost(Type t)
{
while(t.IsGenericType)
{
t = t.GetGenericArguments()[0];
}
return t;
}
then you can do:
var myName = GetInnermost(typeof(TResult)).Name;
then e.g.
RequestData<List<IEnumerable<Task<IObserverable<string>>>();
will have a name of String
.
Upvotes: 2
Reputation: 38608
You could use the GetGenericArguments
method, which returns an array of Type objects that represent the type arguments of a generic type or the type parameters of a generic type definition.
(MSDN).
For sample:
public void RequestData<TResult>()
{
var myName = typeof(TResult).Name;
var type = typeof(TResult)
if (type.IsGenericType)
{
myName = type.GetGenericArguments().First().Name;
}
}
Upvotes: 1
Reputation: 56536
That can be done with the help of a few methods on the Type
.
public void RequestData<TResult>()
{
Type type = typeof(TResult);
string myName;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
myName = type.GetGenericArguments()[0].Name;
}
else
{
myName = typeof(TResult).Name;
}
}
Upvotes: 3