dnndeveloper
dnndeveloper

Reputation: 1631

Generic T get type from class

How can I get this to work? var x = error type or namespace name expected.

class Program
{
    static void Main(string[] args)
    {
        Person j = new John();
        var t = j.GetType();
        var x = new List<t>();
    }
}

class John : Person
{

}

class Person
{
    public string Name;
}

Upvotes: 0

Views: 1527

Answers (3)

Preet Sangha
Preet Sangha

Reputation: 65486

You can do it, but you have to use reflection to do so.

    static void Main(string[] args)
    {
        Person j = new John();
        var t = j.GetType();
        Type genType = Type.MakeGenericType(new Type[] { typeof(List<>) });
        IList x =  (IList) Activator.CreateInstance(genType, t);        
    }

or really simply:

    static void Main(string[] args)
    {
        Type genType = Type.MakeGenericType(new Type[] { typeof(List<>) });
        IList x =  (IList) Activator.CreateInstance(genType, typeof(John)); 
    }

You'll have to use the IList Interface as you need to add stuff to the list

Upvotes: 3

user925777
user925777

Reputation:

Because generics must be known at compile time. In List<T>, T must be a constant type, for example List<Person>.

Upvotes: 2

Jon
Jon

Reputation: 437336

It is not possible to use generics like that. All type parameters of generic classes and functions have to be known at compile time (i.e. they have to be hardcoded), while in your case the result of j.GetType() can only be known at run time.

Generics are designed to provide compile-type safety, so this restriction cannot be lifted. It can be worked around in some cases, e.g. you can call a generic method with a type parameter that is only known at compile time using Reflection, but this is generally something you should avoid if possible.

Upvotes: 3

Related Questions