tags:

views:

76

answers:

2

I new to c# and I am trying to create a method which takes a string and then it instantiates an object using the string as a type.

public void CreateRepository( string name) { 
      var repository = new Repository<name>();
}

e.g.

enter code here

Obviously I get a compiler error but how do I convert my string to a namespace?

A: 

You need to use reflection in order to instantiate this way.
Take a look here for example.

Itay
+4  A: 

You can do it in this way:

public void CreateRepository(string name)
{
    var type = Type.GetType(name);
    var genericRepositoryType = typeof(Repository<>).MakeGenericType(type);
    var repositoryObj = Activator.CreateInstance(genericRepositoryType );
    // N.B. repositoryObj variable is System.Object
    //      but is also an istance of Repository<name>
}
digEmAll