Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a string name to resolve to an object (i.e. in the sense of what it is)

Tags:

c#

oop

factory

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.

like image 751
descf Avatar asked Jan 20 '23 17:01

descf


2 Answers

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.

like image 131
Andrew Hare Avatar answered Jan 23 '23 06:01

Andrew Hare


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

like image 30
Sachin Shanbhag Avatar answered Jan 23 '23 07:01

Sachin Shanbhag