Search code examples
c#dynamicreturnanonymous-objects

C# return (dynamic or anonymous?) object with return values from other methods as properties


I would like to return an object, which stores the return values from other class methods as properties on the return object. The problem is that I do not know which is the best way to do this in C#. Currently I am using a sort of JavaScript-ish approach. Because I do not know the return type, I use the dynamic keyword.

class Test {

    public static dynamic MyExportingMethod() {
        return new {
            myString = MyStringMethod(),
            myInt = MyIntMethod()
        };
    }

    public static string MyStringMethod() {
        return "Hello";
    }

    public static int MyIntMethod() {
        return 55;
    }

   }

And then being able to access them like so,

var myReturnObjWithProps = Test.MyExportingMethod();
myReturnObjWithProps.myString; // should be "Hello"

So my questions are, should I use the dynamic return type? Am I not just returning an anonymous object?


Solution

  • should I use the dynamic return type?

    Yes - a method that returns dynamic effectively returns an object, so you have to use dynamic in order to access it's properties at runtime without reflection.

    Am I not just returning an anonymous object?

    You are, but the declared type of the method is effectively object so its properties cannot be referenced at compile-time.

    Bottom line - you should avoid returning anonymous types from methods if at all possible. Use a defined type, or keep the creation and usage of the anonymous type in one method so you can use var and let the compiler infer the type.