Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return Anonymous Type from method?

I know I can't write a method like:

public var MyMethod() {    return new{ Property1 = "test", Property2="test"}; } 

I can do it otherwise:

public object MyMethod() {    return new{ Property1 = "test", Property2="test"} } 

but I don't want to do the second option because, if I do so, I will have to use reflection.


Why I want to do that:

Today i have a method inside my aspx page that returns a datatable as result and I cannot change it, I was trying to convert this DataTable to an Anonymous method with the properties that I want to work with. I didn't want to create a class only to do that and as I will need to perform the same query more than one time, I Thought to create a method that returns an anonymous type would be a good ideia.

like image 464
Cleiton Avatar asked Aug 25 '09 17:08

Cleiton


People also ask

How do I return an anonymous function in C#?

Try this: Func<string> temp = () => {return "test";}; You can now execute the function thusly: string s = temp();

Do anonymous types work with Linq?

You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.

What is the difference between an anonymous type and a regular data type?

The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.


2 Answers

Returning it as a System.Object is the only way to return an anonymous type from a method. Unfortunately there is no other way to do this since anonymous types were designed specifically to prevent their use in this way.

There are some tricks that you can do to in conjunction with returning an Object that allow you to get close. If you are interested in this workaround please read Can't return anonymous type from method? Really?.

Disclaimer: Even though the article I linked does show a workaround that doesn't mean it is a good idea to do it. I would strongly discourage you using this approach when creating a regular type would be safer and easier to understand.

like image 116
Andrew Hare Avatar answered Oct 01 '22 20:10

Andrew Hare


Alternatively, you can use the Tuple class in .NET 4.0 and higher:

http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

Tuple<string, string> Create() { return Tuple.Create("test1", "test2"); }  

then you can access the properties like this:

var result = Create(); result.Item1; result.Item2; 
like image 28
The Light Avatar answered Oct 01 '22 20:10

The Light