0

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? } 
3
  • 6
    Can you tell us why the return type of myObjectMethod is object? Commented Nov 29, 2011 at 22:53
  • I cant do x. it doesnt show options to choose from but the options like tostring etc Commented Nov 29, 2011 at 22:55
  • @ChaosPandion Object[] myObj = new Object[3]; myObj[0] = "string here"; // myObj[1] = true; //boolean myObj[2] = 1 ; // integer Commented Nov 29, 2011 at 23:16

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You might as well add dynamic to your answer.
@ChaosPandion - I actually added it before I saw your comment -- brilliant minds... :)
string somePropertyValue = ((dynamic)x).SomeProperty; where do I add that
@auto wherever you want to access that property :)
5

Change

private object myObjectMethod(){ ... return myObject; } 

to

private TypeOfMyObject myObjectMethod(){ ... return myObject; } 

Comments

1

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; 

Comments

1

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.