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?
* */
}
}
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();
It is not possible to cast to a type not known at compile-time.
Have a look at the .NET 4.0 dynamic type.
Type fooObjType = fooObj.GetType();
MethodInfo method = fooObjType.GetMethod("FooHasAMethod");
method.Invoke(fooObj, new object[0]);
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