-1

Is there any way to determine a object's type based on a string, then create a new instance of that object?

I am currently doing something like this:

switch (type_str){
  case "Square":
    Square S = new Square();
    S.DoSomethingSquarey();
    DoSomething(S);
    break;
  case "Circle":
    Circle C = new Circle();
    C.DoSomethingCircley();
    DoSomething(C);
    break;
  case "Triangle":
    Triangle T = new Triangle();
    T.DoSomethingTriangley();
    DoSomething(T);
    break;
}

All types will inherit from base class "Shape":

public static void DoSomething(Shape S){
   //Doing Stuff...
}

This will quickly get out of hand to maintain as I will need to continually add shapes to the case statement. If possible, I'd like to do something like this:

Type ShapeType = Type.GetType("Square");
ShapeType X = new ShapeType();
DoSomething(X);

This will cause issues at compile time. Is there another way to simplify this case statement?
Thanks in advance.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Joey Rizza
  • 63
  • 2
  • 6
  • Like this [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx)? – DavidG Jan 12 '17 at 17:40
  • 1
    There's also Reflection. This has been answered here: http://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp – CDove Jan 12 '17 at 17:41
  • 1
    Why is comparing it as a string a requirement? I don't recommend using [magic strings](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants) in code generally. Everything you're trying to do becomes multiple times easier if you use the [Type](https://msdn.microsoft.com/en-us/library/58918ffs.aspx) instead of a string. – Erik Philips Jan 12 '17 at 17:47

1 Answers1

0

You can scan current assembly (or whatever assembly that contains your shapes) for types that inherited from Shape, and use Activator.CreateInstance to create the instance. It's better if you cache the name and type in a dictionary, so you can quickly lookup the type that you want.

var type_str = "Circle";

// TypeChache should be static field
if (TypeChache == null)
{
    var assem = Assembly.GetExecutingAssembly();
    TypeChache = assem.GetTypes()
                 .Where(x => typeof(Shape).IsAssignableFrom(x))
                 .ToDictionary(x=>x.Name, x=>x);
}

var type = TypeChache[type_str];    
var inst = (Shape) Activator.CreateInstance(type);
DoSomething(inst);
Niyoko
  • 7,512
  • 4
  • 32
  • 59