stacker flow stacker flow - 2 months ago 10
C# Question

How to get type of custom class from string c#

I am trying to use GetType method for my custom class . I have the name of the class as string and i want to get type of it dynamically. I have the same name for two different classes which are located in different directories.

For Example:

MyClass.cs in Folder1:

namespace ConsoleApplication1.Folder1
{
public class MyClass : IClass
{
public void PrintMe()
{
System.Console.WriteLine("I am Folder 1 Class");
}
}
}


MyClass.cs in Folder2:

namespace ConsoleApplication1.Folder2
{
public class MyClass : IClass
{
public void PrintMe()
{
System.Console.WriteLine("I am Folder 2 Class");
}
}
}


Namespace is ConsoleApplication1

different classes with the same name are in the Folder1 and Folder2.

I want to get it's type from such a string:

var runtimeString = "Folder1.MyClass"


There is method mentioned in MSDN named GetType(string fileName)

How can i get type of the file and resolve it from the serviceLocator with type on runtime like:

var typeOfMyClass = GetType(runtimeString);
var instanceOfMyClass = ServiceLocator.Resolve<TypeOfMyClass>();

Answer

You appear to be describing a need for a factory method, something along the lines of:

public class MyClassFactory : IMyClassFactory
{
    private Dictionary<string, Action<IClass>> _factory =
        new Dictionary<string, Action<IClass>>
        {
            ["Folder1.MyClass"] = () => new ConsoleApplication1.Folder1.MyClass(),
            ["Folder2.MyClass"] = () => new ConsoleApplication1.Folder2.MyClass(),
            ...
        };

    public IClass GetClassInstance(string myClassName)
    {
        if (_factory.Contains(myClassName))
        {
            return _factory[myClassName]();
        }
        throw NoSuchClassException(myClassName);
    }
} 
Comments