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.
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.
Check Activator.CreateInstace(Type) or Activator.CreateInstance(string, 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