0

I have 12 classes in my project like this:

class class1
{

}

class class2
{

}

in another class I have a method that I want to create an instance of class1 or class2 according to a string:

public void MyMethod(string s)
{
//I want to create an instance of class1 if s=="class1" or class2 if s=="class2"
} 

How I can do this?

3

1 Answer 1

2

Here is a work around try this hope it will work.

First you need to pass class actual name in string, e.g if you have a class ClassA then Pass ClassA to this one it will create an instance of the class.

private object MyMethod(string className)
{
    var assembly = Assembly.GetExecutingAssembly();

    var type = assembly.GetTypes()
    .First(t => t.Name == className);

    return Activator.CreateInstance(type);
}
3
  • In this case I can't access to Methods of class because it is an object.
    – mohammad
    Commented Mar 15, 2014 at 12:13
  • 1
    you got it wrong this is not object it's returning object of your desired class. Commented Mar 15, 2014 at 12:19
  • i declared this method as static that's why you wouldn't be able to access it from non-static types. Now i changed it to non-static method now it will become available to your intelli-sense. Commented Mar 15, 2014 at 12:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.