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

Recommended Answers

All 2 Replies

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);
Assembly asm = Assembly.GetExecutingAssembly();

Object myObj = asm.CreateInstance("Some.Object.Name");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.