Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a generic method with a dynamic type [duplicate]

Tags:

c#

generics

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?

like image 445
cmptrer Avatar asked Nov 04 '10 21:11

cmptrer


People also ask

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

What is dynamic keyword in C#?

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.

What is generic type constraint?

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.


1 Answers

I don't know about elegant, but the way to do it is:

typeof(Creator)     .GetMethod("CreateAnimals")     .MakeGenericMethod(type)     .Invoke(creator, new object[] { 5 }); 
like image 88
Kirk Woll Avatar answered Oct 23 '22 14:10

Kirk Woll