If you are using .NET 4, it is really very simple = D
dynamic obj = bar; obj.FooProperty.FooHasAMethod();
However, if you just want to pass the result to another type, you can do this at run time using the Convert.ChangeType method:
object someBoxedType = new Foo(); Bar myDesiredType = Convert.ChangeType(typeof(Bar), someBoxedType) as Bar;
Now it has a strong connection with the actual types Foo and Bar. However, you can generalize 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 call like this:
Bar x = GetObjectAs(someBoxedType, new Bar()); SomeTypeYouWant x = GetObjectAs(someBoxedType, Activator.CreateInstance(typeof("SomeTypeYouWant")));
Using an activator, you can create at runtime any type you want. And the general method is fooled by output in an attempt to convert from your boxedType to a runtime type.
Also, if you just want to call the method for some dynamic property value, then it would be best practice (imo) to simply pass it as some desired object.
ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething; if(propValue != null) propValue.FooHasAMethod();
source share