Click here to Skip to main content
15,884,425 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Say we have a class like this :
C#
public class someclass<T> : Iinterface {}

And we have a function like this:
C#
public Iinterface Create(Type type)
{
// how to return ?
}

How can we return an instance of the someclass based on a parameter say typeof(int) in the Create method without ugly "if then" or "switch" statements?
Posted

Type finalType = typeof(someclass<>);
return Activator.CreateInstance(finalType.MakeGenericType(type));


See also this blog[^] which a Google search turned up.
 
Share this answer
 
Comments
Mehdi Gholam 16-Feb-12 6:02am    
Great it works! I had to pass args to the ctor but that's ok.

My 5!
see this:
Generics in C# 2.0[^]
 
Share this answer
 
Reflection allows you to create objects dynamically:
C#
string myType = "MyNamespace.MyClass";
Assembly asm = Assembly.GetExecutingAssembly();
Type t = asm.GetType(myType);
Object o = Activator.CreateInstance(t, null, null);
So in your case, you would need just the last line.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900