obautista
obautista

Reputation: 3773

How to use GetType on a generic type using Reflection

Is it possible using reflection to get type of a generic class? My generic class:

public class ItemResponse<TItem>: ItemBase where TItem: Item
{
    public bool HasMore { get; set; }
    public List<TItem> Items { get; set; }
    public int Offset { get; set; }
    public int TotalResults { get; set; }
}

Debit class inherits from Item:

public class Debit: Item
{
   public string ABBREVTYPE { get; set; }
}

Item from ItemBase:

public class Item: ItemBase
{
    public string CREATEDBY { get; set; }
}

Is it possible using Type.GetType to get ItemResponse?

Something like this (this is the part I dont know about):

var myType = "namespace.ItemResponse[namespace.Debit]";
var genericItemType = Type.GetType(myType);

Upvotes: 0

Views: 268

Answers (2)

Rufus L
Rufus L

Reputation: 37070

You're missing the `1 in your type name. Something like this should work:

var myType = "Namespace.ItemResponse`1[Namespace.Debit]"
var genericItemType = Type.GetType(myType);

Upvotes: 0

J Allen
J Allen

Reputation: 38

You can find 'ItemResponse' from GetType() or typeof();

var type = typeof(ItemResponse<Debit>);
Console.WriteLine(type.Name);//prints ItemResponse`1
Console.WriteLine(type.FullName);//prints MyApp.ItemResponse`1[[MyApp.Debit, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

It's in both the FullName property of the type object.

Upvotes: 1

Related Questions