Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
         * */
    }
}
like image 965
nobody Avatar asked Apr 07 '11 15:04

nobody


3 Answers

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();
like image 156
Tejs Avatar answered Oct 05 '22 22:10

Tejs


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

Have a look at the .NET 4.0 dynamic type.

like image 32
David Neale Avatar answered Oct 05 '22 22:10

David Neale


Type fooObjType = fooObj.GetType();
MethodInfo method = fooObjType.GetMethod("FooHasAMethod");
method.Invoke(fooObj, new object[0]);
like image 26
Arturo Martinez Avatar answered Oct 06 '22 00:10

Arturo Martinez