Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare a Func with an anonymous return type?

I need to be able to do this:

var getHed = () =>  {     // do stuff     return new { Property1 = value, Property2 = value2, etc...}; };  var anonymousClass = getHed(); 

But I get an error which indicates I need to explicitly declare getHed.

How do I declare Func such that T is the anonymous type I am returning?

In case you are curious why I need to do this, it is because I am using 3rd party software that allows customization code, but only within a single method. This can become very difficult to manage. I had the idea that I could use anonymous methods to help keep the procedural code organized. In this case, for it to help, I need a new class, which I cannot define except anonymously.

like image 332
Price Jones Avatar asked Dec 14 '16 20:12

Price Jones


People also ask

How do I return anonymous type?

As in the preceding facts you cannot return an anonymous type from a method, if you do want to return one then you need to cast it to an object.

How do I return an anonymous function in C#?

string temp = ((Func<string>)(() => { return "test"; }))(); string temp = new Func<string>(() => { return "test"; })(); Note: Both samples could be shorted to the expression form which lacks the { return ... } Thanks.

How do you define anonymous type?

Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.

What keyword do you use to declare an anonymous type?

The anonymous type declaration starts with the new keyword. The declaration initializes a new type that uses only two properties from Product . Using anonymous types causes a smaller amount of data to be returned in the query.


1 Answers

As is basically always the case with anonymous types, the solution is to use a generic method, so that you can use method type inference:

public static Func<TResult> DefineFunc<TResult>(Func<TResult> func) {     return func; } 

You can now write:

var getHed = DefineFunc(() =>  {     // do stuff     return new { Property1 = value, Property2 = value2, etc...}; }); 
like image 58
Servy Avatar answered Oct 04 '22 08:10

Servy