1

I have created an object with a boolean property and a collection.

what I do:

I have a method that gets called when on post which in turn calls another method that returns an object. my problem is that I don't get the object properties.

public object methodThatReturnsAnObject(string a, string b)   
{
    object data = new {isSaved = false, personsToCredit = ""}

    // perform my code and if all is valid i set values to my object properties and return the object

    data = new {isSaved = valid, personsToCredit = persons }

    return data;    
}

My other method:

object Information = methodThatReturnsAnObject(string a, string b);

whats my problem? When I debug the Information object contains the two properties that I want to get my hands on BUT when I type Information.isSaved it says that information does not contain a definition for isSaved?

rcs
  • 67,191
  • 22
  • 172
  • 153
ThunD3eR
  • 3,216
  • 5
  • 50
  • 94

1 Answers1

7

You are expecting the compiler to know that your object will have those dynamic properties.

This is just your basic object-orientation that you must use properly.

What you need to do is either (1) define a specific class with the two properties and let your method return that class instead, or (2) use dynamic instead of object.

Example of approach #1:

public class UpdateInfo
{
    public bool IsSaved {get; set;}

    ...
}


public UpdateInfo MethodThatReturnsUpdateInfo(string a, string b)
{
    ...
}

You should use dynamic only in case you cannot use approach #1, but I'd say that in 99.9% of all cases, approach #1 is the way to go.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • If *really* necessary, you could cast the return value to the anonymous type: http://stackoverflow.com/questions/1409734/cast-to-anonymous-type. But I don't see the point. Much better to define a class or interface. – Oliver Sep 16 '13 at 08:23
  • Thanks alot @Roy Dictus! im going to go with the dynamic approach this time since its a rather big project and i don't want to add an extra class for this. I learned something new here, thx alot! – ThunD3eR Sep 16 '13 at 08:31
  • 1
    @Ra3IDeN Why do you not want to add a class? It's safer to do so, as you will get compile time checking of your code. – Oliver Sep 16 '13 at 08:33
  • @Oliver at this moment it is cuz im lazy and want to get this to work. been at it for a while. I will probably change it later on and use a class but at this moment ill be happy with the dynamic so i can see the result of what im trying to do. – ThunD3eR Sep 16 '13 at 08:35