0

I have a string "MyClass". Is there any way to initialize a generic object by string?

public void LoadToCache<T>(string key) where T : class, new()
{
  //string key is a class name like "MyClass"
    using (var bl = new BusinessLayer<key>())
    {
       bl.GetAll();
    }
} 
//---------------------------------------------------------------
public class BusinessLayer<T> where T : class
{
  ..
  ..
}
//---------------------------------------------------------------
public class MyClass
{
  ..
  ..
}
Moinul Islam
  • 469
  • 2
  • 9
  • 2
    Try to use [MakeGenericType](https://msdn.microsoft.com/en-us/library/system.type.makegenerictype) – Aleks Andreev Jun 05 '18 at 17:25
  • 1
    You can do that using reflection like Aleks suggested, but you may not be able to use the instance as you expect. Since the compiler won't know the type of the instance at runtime, you will not be able to call `GetAll()` (except again via reflection or by using `dynamic`). It seems you have a design flaw and an [xy-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here. If you add context about _what you are actually trying to achieve_ someone may show you a better overall approach. – René Vogt Jun 05 '18 at 17:27
  • Possible duplicate of [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](https://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class) – Dmitry Pavliv Jun 05 '18 at 17:31
  • @Dmitry Pavliv in that is it possible to use bl.GetAll()? – Moinul Islam Jun 05 '18 at 17:37
  • @RenéVogt. I have string list which contains class name. And I also have a generic type repository class. My task is read string from the list and call repository method. – Moinul Islam Jun 05 '18 at 17:47

1 Answers1

-1

You could get the types from your assembly by reflection and create a instance using Activator.CreateInstance.

I Hope this helps:

My class:

public class Car
{

}

The method:

string myClass = "Car";
var types = Assembly.GetExecutingAssembly().GetTypes().ToList();
var myType = types.FirstOrDefault(i => i.IsClass && i.Name == myClass);
var instance  = Activator.CreateInstance((Type) myType);

Console.Write(instance.ToString());