0

In C#, how to instantiate an object against a class; but the class name is in a string variable?**

String stringNameOfClass = "SomeClass";
{stringNameOfClass} theObject = new {stringNameOfClass}();

In js, i think we could use eval()

var stringNameOfClass = "SomeClass";
eval('var theInstance = new ' + stringNameOfClass + '()');
theInstance.accessMethod();

[EDIT] Given: Classes name are unknown But methods are known

I can get all classes name in a given folder. Now I want to instantiate each of them accordingly by their namespace. Though, I know the method i'm interested in.

arrayOfString = getAllClassesByNamespace('TheNamespace','/path');
// now call testMe() per instance
foreach (string str in arrayOfString )
{
{str} arrayOfString[str] = new {str};
str.testMe();
//in js
eval('var obj_' + arrayOfString[str] + ' = new ' + arrayOfString[str] + '()');
//if first class found is TheClass.. this is what I want to do
TheClass obj_TheClass = new TheClass();
obj_TheClass.testMe();
}
Tyro Hunter
  • 755
  • 1
  • 8
  • 20
  • 7
    What are you _actually_ trying to do? In most cases questions regarding "cast string to class" are [XY problems](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and can often be answered with: use a `Dictionary` (instead of the obvious reflection approach). – Tim Schmelter Mar 06 '15 at 08:55
  • 5
    I'm guessing you are after [`Activator.CreateInstance`](https://msdn.microsoft.com/en-us/library/system.activator.createinstance%28v=vs.110%29.aspx), but it is important that C# probably has a better way of doing whatever you're trying to do. What are you trying to achieve? – Sayse Mar 06 '15 at 08:56
  • 3
    possible duplicate of [c# instantiate class from string](http://stackoverflow.com/q/2247598/50447) – Rowland Shaw Mar 06 '15 at 08:56
  • the Class is unkown, so how am I going to do the declaration? `UNKOWNclass theobject = UNKOWNClass(); var stringNameOfClassUNKNOWN = "SomeClass"; eval('var theInstance = new ' + stringNameOfClassUNKNOWN + '()'); theInstance.accessMethod();` – Tyro Hunter Mar 06 '15 at 09:11
  • 1
    But *why* is it unknown? You obviously are expecting whatever class it is to have a method called `accessMethod` so if this is implemented in multiple classes perhaps it is just an interface that you need – Sayse Mar 06 '15 at 09:16
  • Yes it is implemented in multiple classes, but these classes are test cases in unit test, we cannot assume what are their exact names. Ex. DefaultWidgetSizeTestCase, SimpleWidgetTestCase, anotherUnitTestCase etc. – Tyro Hunter Mar 06 '15 at 09:47

2 Answers2

1

I think you are looking for the Activator.CreateInstance method, this will take a number of parameters but there is one that will take a TypeName and Namespace allowing you to create an instance of a new class from it's name.

https://msdn.microsoft.com/en-us/library/d133hta4(v=vs.110).aspx

  • Hi, In my example I expect: TheClass obj_TheClass = new TheClass(); obj_TheClass.testMe(); I believe Activator.CreateInstance needs a cast type, but as you see I have unkown, I can't TheObject = (Uknown)Activator.CreateInstance..... – Tyro Hunter Mar 06 '15 at 09:41
  • Do all the class implement an interface or inherit from a base class? If so you can cast to that. `MyBaseClass obj = (MyBaseClass)Activator.CreateInstance(...)` – Richard Green Mar 06 '15 at 11:37
  • Yes but, casting won't work since I would then have to access the derived classes methods, which i'm not sure if it is possible – Tyro Hunter Mar 13 '15 at 09:00
1

Here's the most straight forward solution I found in how to instantiate a class from string: https://msdn.microsoft.com/en-us/library/a89hcwhh.aspx

public class TestMethodInfo
{
    public static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        String stringedClass = "MagicClass";
        String stringedClassMethod = "theMethod";
        Type magicType = Type.GetType(stringedClass);
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo magicMethod = magicType.GetMethod(stringedClassMethod);
        object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

        Console.WriteLine("MethodInfo.Invoke() Example\n");
        Console.WriteLine("MagicClass.theMethod() returned: {0}", magicValue);
    }
}

Cheers!

Tyro Hunter
  • 755
  • 1
  • 8
  • 20