Reputation: 28284
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?
}
Upvotes: 0
Views: 3298
Reputation: 83358
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 object
being 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:
string val;
if (x is ActualType)
val = (x as ActualType).SomeProperty;
Or, if you know the property name, but not the type of x, then:
PropertyInfo pi = x.GetType().GetProperty("SomeProperty");
string somePropertyValue = (string)pi.GetValue(x, null);
Or, if you're using C# 4, you could use dynamic
string somePropertyValue = ((dynamic)x).SomeProperty;
Just don't go crazy with dynamic. If you find yourself using dynamic
excessively, there may be some deeper issues with your code.
Upvotes: 8
Reputation: 7181
You could use a generic version of your method:
public static T MyObjectMethod<T>()
{
return (T)myObject;
}
And then:
var myObject = MyObjectMethod<MyObjectClass>();
myObject.Property;
Upvotes: 1
Reputation: 5139
You should change the return type of your method to the actual class you're interested in. And probably you'll need to change it's visibility to public.
You can also use reflection or casting
(obj as MyObject).Stuff;
Upvotes: 1
Reputation: 172220
Change
private object myObjectMethod(){
...
return myObject;
}
to
private TypeOfMyObject myObjectMethod(){
...
return myObject;
}
Upvotes: 5