Lets say I have the following classes
public class Animal { .... } public class Duck : Animal { ... } public class Cow : Animal { ... } public class Creator { public List<T> CreateAnimals<T>(int numAnimals) { Type type = typeof(T); List<T> returnList = new List<T>(); //Use reflection to populate list and return } }
Now in some code later I want to read in what animal to create.
Creator creator = new Creator(); string animalType = //read from a file what animal (duck, cow) to create Type type = Type.GetType(animalType); List<animalType> animals = creator.CreateAnimals<type>(5);
Now the problem is the last line isn't valid. Is there some elegant way to do this then?
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it. dynamic cust = GetCustomer(); cust.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
I don't know about elegant, but the way to do it is:
typeof(Creator) .GetMethod("CreateAnimals") .MakeGenericMethod(type) .Invoke(creator, new object[] { 5 });
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