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?

mohammad
  • 1,248
  • 3
  • 15
  • 27

1 Answers1

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);
}
Aftab Ahmed
  • 1,727
  • 11
  • 15
  • In this case I can't access to Methods of class because it is an object. – mohammad Mar 15 '14 at 12:13
  • 1
    you got it wrong this is not object it's returning object of your desired class. – Aftab Ahmed Mar 15 '14 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. – Aftab Ahmed Mar 15 '14 at 12:25