Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class by string value

Tags:

I have an abstract class with a few derived class

public abstract class MyObject {     public string name { get; set; }     public bool IsObject(string pattern);     ... }  public class MyObjectA : MyObject {     public string name { get { return "MyObjectA"; } set; }     public bool IsObject(string pattern) { ... }     ... }  public class MyObjectB: MyObject {   public string name { get { return "MyObjectB"; } set; }   public bool IsObject(string pattern) { ... }   ... } 

Now I want to have a function, which returns my the specific class (MyObjectA / MyObectB) based on a string. The problem is, that I have a lot of if/else-clauses to get that:

public MyObject Create(string pattern) {     MyObjectA obj = new MyObjectA();     if(obj.IsObject(pattern)     {         return obj;     }     else     {         MyObjectB objb = new MyObjectB();         if(objb.IsObject(pattern);             return objb;         else             ...     } } 

That looks just awful. What would be a better way to do this?

like image 722
Link Avatar asked Dec 19 '12 12:12

Link


People also ask

How to get the class object of a class?

Object. getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() .

Can I inherit from String class?

The string class is marked sealed because you are not supposed to inherit from it. What you can do is implement those functions elsewhere. Either as plain static methods on some other class, or as extension methods, allowing them to look like string members.


2 Answers

Yes, use Reflection.

You can use Type.GetType to get an instance of the Type for the class by string, then instantiate it using Activator.CreateInstance, something like this:

public MyObject Create(string pattern) {     Type t = Type.GetType(pattern);     if (t == null) {         throw new Exception("Type " + pattern + " not found.");     }     return Activator.CreateInstance(t); } 

You could use Activator.CreateInstance(string, string) overload also, but this would not directly return a new instance of the Type required.

like image 72
Rudi Visser Avatar answered Oct 20 '22 05:10

Rudi Visser


You can use Reflection or System.Activator.CreateInstance to create an instance based on the Type or TypeName as string.

like image 32
dutzu Avatar answered Oct 20 '22 03:10

dutzu