Returning Anonymous Types in C#
In C#, anonymous types are a convenient way to create temporary objects with custom properties. However, when it comes to returning anonymous types from a method, there's a limitation.
Problem:
How do you return an anonymous type from a method, considering the following code:
public "TheAnonymousType" TheMethod(SomeParameter) { using (MyDC TheDC = new MyDC()) { var TheQueryFromDB = (.... select new { SomeVariable = ...., AnotherVariable = ....} ).ToList(); return "TheAnonymousType"; } }
Answer:
Unfortunately, it's not possible to return an anonymous type directly from a method in C#.
The reason lies in the fact that anonymous types are compiled at runtime and do not have a known type at the time of compilation. Therefore, they cannot be returned as a specific named type, such as "TheAnonymousType" in your example.
Solution:
To workaround this limitation, you have two options:
The above is the detailed content of How Can I Return Anonymous Types from a C# Method?. For more information, please follow other related articles on the PHP Chinese website!