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.
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.
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.
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.
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.
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...}; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With