Type casting in c# using the string name of the object type

25,558

Solution 1

Type fooObjType = fooObj.GetType();
MethodInfo method = fooObjType.GetMethod("FooHasAMethod");
method.Invoke(fooObj, new object[0]);

Solution 2

If you're using .NET 4, it's actually really easy =D

dynamic obj = bar;
obj.FooProperty.FooHasAMethod();

However, if you just want to cast the result to some other type, you can do that at runtime with the Convert.ChangeType method:

object someBoxedType = new Foo();
Bar myDesiredType = Convert.ChangeType(typeof(Bar), someBoxedType) as Bar;

Now, this one has a strong link to the actual types Foo and Bar. However, you can genericize the method to get what you want:

public T GetObjectAs<T>(object source, T destinationType)
   where T: class
{
     return Convert.ChangeType(typeof(T), source) as T;
}

Then, you can invoke like so:

Bar x = GetObjectAs(someBoxedType, new Bar());

SomeTypeYouWant x = GetObjectAs(someBoxedType, Activator.CreateInstance(typeof("SomeTypeYouWant")));

Using the activator, you can at runtime create any type you want. And the generic method is tricked by inference into attempting a convert from your boxedType to the runtime type.

In addition, if you want to just call a method on some dynamic property value, then the best practice (imo), would be to simply cast it as some desired object.

ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething;

if(propValue != null)
    propValue.FooHasAMethod();

Solution 3

It is not possible to cast to a type not known at compile-time.

Have a look at the .NET 4.0 dynamic type.

Solution 4

There's no way to cast by using string. But you can use dynamic, or MethodInfo with invoke

Share:
25,558
nobody
Author by

nobody

Updated on March 10, 2020

Comments

  • nobody
    nobody about 4 years

    I have the following code, should be easy to follow through

    public class Foo
    {
        public void FooHasAMethod()
        {
            Console.WriteLine("it is me, foo!!!");
        }
    }
    
    public class Bar
    {
        public Foo FooProperty { get; set; }
    }
    
    public class FooBar
    {
        public static void Main()
        {
            Bar bar = new Bar{ FooProperty = new Foo() };
            CallPropertyByName(bar, "Foo");
        }
    
        public static void CallPropertyByName(Bar bar, string propertyName)
        {
            PropertyInfo pi = bar.GetType().GetProperty(propertyName + "Property");
            object fooObj = pi.GetValue(bar, null);
            ((Foo)fooObj).FooHasAMethod(); // this works
            /* but I want to use 
             * ((Type.GetType(propertyName))fooObj).FooHasAMethod(); This line needs fix
             * which doesnt work
             * Is there a way to type cast using a string name of a object?
             * */
        }
    }
    
  • SLaks
    SLaks about 13 years
    If T is a class, Convert.ChangeType is useless (unless you're using IConvertible).
  • Tejs
    Tejs about 13 years
    The conversion can fail of course, with an exception. I have a particularly large GenericConverter extension method so I can simply say anyObject.ConvertTo<DateTime>() for example.