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;
}
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.