I have a method that returns an object:
private object myObjectMethod(){
//...
return myObject;
}
But in another method I want to retrieve this object:
private void myotherMethod(){
var x = myObjectMethod();
// Now how would I access the properties of myObject?
}
The best way is to just return the actual type you’re dealing with from the method
But if that’s not an option, and you really are stuck with just
objectbeing returned from your method, you have a few options.If you know the right type, casting would be the simplest way:
((ActualType)x).SomeProperty;Or to test that the cast is correct:
Or, if you know the property name, but not the type of x, then:
Or, if you’re using C# 4, you could use
dynamicJust don’t go crazy with dynamic. If you find yourself using
dynamicexcessively, there may be some deeper issues with your code.