tags:

views:

103

answers:

5

i want to create instance of any class by generic way. is that possible?i know ,this is madly but this is only a question waits the its answer.

i tried this but doesnt work.

public class blabla {
 public void bla();
}

public class Foo<T>
{

        Dictionary<string, Func<object>> factory;

        public Foo()
        {
          factory = new Dictionary<string, Func<object>>();
        }

        public WrapMe(string key)
        {

            factory.Add(key, () => new T());

        }
 }

 Foo<blabla> foo = new Foo<blabla>();
 foo.Wrapme("myBlabla");
 var instance = foo.factory["myBlabla"];
 instance.Bla();
+4  A: 

There are two ways to solve this:

Variant 1: Add where T : new() to your class definition:

public class Foo<T> where T : new()
{
    ...
}

For further details, see the description of the new() constraint.


Variant 2: Pass the lambda () => new T() as a parameter to your constructor, store it in a Func<T> field and use it in WrapMe.

For further details, see this blog post

Heinzi
+2  A: 

You only need a method:

static T InstantiateInstance<T>() where T : new()
{
    return new T();
}
grenade
A: 

You need to use the new constraint when declaring Foo. This only works for types with a constructor with no arguments - which is fine in your case.

Phil Nash
+2  A: 

You can use Activator.CreateInstance<T>().

Diego Mijelshon
Yes, better than my approach.
grenade
@grenade - identical to your approach. The only difference is- your approach will fail at compile time, Diego's approach will fail at run time
Krzysztof Koźmic
@Krzysztof Koźmic, care to elaborate? Both approaches compile and run fine here.
grenade
if you don't add new() and use explicit call to Activator, the call will fail when you pass a type w/o default .ctor, that's the failing part.When you add new() contstraint, and then call `var t = new T()` the compiler will emit the call to Activator.CreateInstance<T>(), that's the 'same' part.
Krzysztof Koźmic
+1  A: 

Use an Inversion of Control container, like Castle Windsor.

Krzysztof Koźmic