Create intance of any C # class in a common way

I want to instantiate any class in a common way. is it possible? I know this is crazy, but this is just a question waiting to be answered.

I tried this but it does not 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();
+1
source share
5 answers

You only need a method:

static T InstantiateInstance<T>() where T : new()
{
    return new T();
}
+2
source

There are two ways to solve this problem:

Option 1 : add where T : new()to your class definition:

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

For more details see the description of the new () constraint .


Option 2 : pass lambda () => new T()as a parameter to your constructor, save it in a field Func<T>and use it in WrapMe.

See this blog post for more details.

+4
source

Activator.CreateInstance<T>().

+2

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

0
source

All Articles