Home > Software design >  Instantiate C# class object using the string name
Instantiate C# class object using the string name

Time:03-26

Is it possible to instantiate a class object having the name coming from string?

string objectName = “abc”;
MyClass objectName = new MyClass();

I want the class object to be generated as:

MyClass abc = new MyClass();

CodePudding user response:

I think you can use Dictionary<string,MyClass>

    Dictionary<string,MyClass> _dict = new Dictionary<string,MyClass>();
    public void CreateObject(string name){
        if(!_dict.ContainsKey(name)){
          _dict.Add(name,new MyClass());
        }
    }
    public MyClass Get(string name){
        return _dict[name]; // only demo without nullable check
    }

CodePudding user response:

I think you're talking about

Dictionary<key, value>

This might help you, do something like this

    string objectName = “abc”;
    Dictionary<string, MyClass> obj= new Dictionary<string, MyClass>();
    obj[objectName] = new MyClass();
  • Related