I want to do something like this:
public List<T> GetList<T>()
{
if (typeof(T) == typeof(Type1))
{
return new List<Type1>() { new Type1(), new Type1(), new Type1() };
}
if (typeof(T) == typeof(Type2))
{
return new List<Type2>() {new Type2(), new Type2()};
}
throw new Exception("Unknown T");
}
public void DoStuffWithGenericList<T>()
{
var list = GetList<T>();
// do stuff that does not depend on T
}
But that, of course, is not legal. I feel I am missing something basic here :)
In my case, I am getting lists of different types of objects from Entity Framework, but the rest of my logic does not depend on the actual type. It can just work on List or it could be generic.
All Ts that GetList() will be called with as type parameter will inherit from the same base class, if it makes a difference.
Why not use the 'new' operator to instantiate the types:
public List<T> GetList<T>() where T : new()
{
if (typeof(T) == typeof(Type1))
{
return new List<T>() { new T() };
}
// etc...
throw new Exception("Unknown T");
}
All you have to do is ensure your types can be instantiated by adding the new() constraint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With