Question

I know there are a lot of questions about C# anonymous types, but none of them answers me. I also know that you can return anonymous types, either assigning the result of the method to a dynamic object or casting it as this article by Jon Skeet states, but in both cases you need to know which are the members of the anonymous object, so why can't we have a sort of keyword named anonymous which allow us to do things like this:

anonymous F()
{
    ...
    return new { a = 5, b = "some string" };
}

and then using it like this:

anonymous a = F();

but having static typing? I mean, why isn't the compiler able to know statically which are the members of the anonymous object F method returns, and so give me intellisense?

Was it helpful?

Solution

What would you stop than from doing something like this:

anonymous F()
{
     if (something) return new { a = 5 };
     else return new { b = 1, z = "asdf" };
}

How is compiler supposed to know which type is returned then? Should it limit you at design time with error messages that those anonymous types are not the same? Is it worth the effort? You can use dynamic for such cases or create actual classes if needed - to make code clear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top