0

Hello,

I have a list of strings. It contains strings with NAMES of my objects. This mean:

First f1 = new First();
Sec f2 = new Sec();
Third f3 = new Third();

And my list contain:

List<string> smth = new List<string>();
First,
Sec,
Third

How can I create object knowing only its name?

foreach(string ex in smth)
{
  //and what now?
}
3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Momerath
0

If you create a base class that your individual classes inherit, and then an enum containing the names of your classes, you can create a new object by passing the enum. Something like:

class BaseClass
{
    public BaseClass(ClassType ct)
    {
        if (ct == ClassType.First)
            return new First();
        // etc.
    }
}

Then obviously:

class First : BaseClass
{ 
    //etc.
}

Then for the enum simply:

enum ClassType
{
    First,
    Second,
    etc
}

Then when you need your object you can do:

BaseClass bc = new BaseClass((ClassType)Enum.Parse(typeof(ClassType), objectType));
//where objectType is the string value of the object you want created, for example, "First"
//if "First" is stored in objectType, this is the same as calling
// BaseClass bc = new BaseClass(ClassType.First);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.