user465154
user465154

Reputation: 35

string literal converted to type or namespace for generics c#

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.

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

Upvotes: 1

Views: 1289

Answers (1)

digEmAll
digEmAll

Reputation: 57210

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>
}

Upvotes: 5

Related Questions