Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecast to a type from just the string representation of the type name

sTypeName = ... //do some string stuff here to get the name of the type

/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to 
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

How do I do that? And, what do I take on the left side of the assignment expression, assuming this is C# 2.0. I don't have the var keyword.

like image 349
Water Cooler v2 Avatar asked Apr 15 '10 09:04

Water Cooler v2


2 Answers

Usually you let all classes, you want to instantiate this dynamically, implement a common interface, lets say IMyInterface. You can create an instance from the classname string like this:

Assembly asm = Assembly.GetExecutingAssembly();
string classname = "MyNamespace.MyClass";
Type classtype = asm.GetType(classname);

// Constructor without parameters
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype);

// With parameters (eg. first: string, second: int):
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype, 
                        new object[]{
                            (object)"param1",
                            (object)5
                        });

Even if you dont have a common interface, but know the name of the method (as string) you can invoke your methods like this (very similar for properties, event and so on):

object instance = Activator.CreateInstance(classtype);

int result = (int)classtype.GetMethod("TwoTimes").Invoke(instance, 
                        new object[] { 15 });
// result = 30

The example class:

namespace MyNamespace
{
    public class MyClass
    {
        public MyClass(string s, int i) { }

        public int TwoTimes(int i)
        {
            return i * 2;
        }
    }
}
like image 149
Philip Daubmeier Avatar answered Oct 13 '22 19:10

Philip Daubmeier


Unfortunately there's no way in .NET to do what you want.

Possible partial solutions are:

  1. If you know the type at compile-time (unlikely, since you're creating it at run-time from a string) then simply cast to that type:

    YourType t = (YourType)Activator.CreateInstance(sTypeName);
    
  2. If you know that all the possible types will implement a specific, common interface then you can cast to that interface instead:

    IYourInterface i = (IYourInterface)Activator.CreateInstance(sTypeName);
    

If you can't do either of the above then, unfortunately, you're stuck with object and reflection.

like image 32
LukeH Avatar answered Oct 13 '22 20:10

LukeH