4

For example I can do something like:

switch (myString)
case "rectangle":
 o = new rect();
 break;
case "ellipse"
 etc...

but how do I not do the above, i.e. just have one line of code that gets the object directly from the string. Imagine, for example, a button and whatever it says when the user clicks it, it takes the displayed text and creates an object from it.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
descf
  • 1,302
  • 1
  • 12
  • 31

4 Answers4

6

If the name is the exact same thing as the string, you can do something like this:

using System;
using System.Reflection;

class Example
{
    static void Main()
    {
        var assemblyName = Assembly.GetExecutingAssembly().FullName;
        var o = Activator.CreateInstance(assemblyName, "Example").Unwrap();
    }
}

A simpler approach would look like this:

using System;
using System.Reflection;

class Example
{
    static void Main()
    {
        var type = Assembly.GetExecutingAssembly().GetType("Example");
        var o = Activator.CreateInstance(type);
    }
}

But keep in mind that this is a very simple example that doesn't involve namespaces, strong-named assemblies, or any other complicated things that crop up in bigger projects.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
2

Check Activator.CreateInstace(Type) or Activator.CreateInstance(string, string)

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
1

He descf,

Have you tried Activator.CreateInstace("assemblyname", "typename");

WraithNath
  • 17,658
  • 10
  • 55
  • 82
0

A Factory pattern would decouple the code from the string. Please take a look at this dofactory page for both the UML and a C# example of the Factory pattern.

Community
  • 1
  • 1
rajah9
  • 11,645
  • 5
  • 44
  • 57