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?
Object. getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() .
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.
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.
You can use Reflection or System.Activator.CreateInstance to create an instance based on the Type or TypeName as string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With