I have the following code, should be easy to follow through
public class Foo
{
public void FooHasAMethod()
{
Console.WriteLine(\"it is me, fo
There's no way to cast by using string. But you can use dynamic, or MethodInfo with invoke
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'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();