I was skimming through Sam's LINQ Unleashed for C# and on page 7 it listed:
Anonymous types can be initialized to include methods, but these might only be of interest to linguists.
I don't really understand if the linguists comment is a joke. Regardless, it is possible to do something like this in C#
var obj = new {
Name = "Joe", Weight = 200,
GetAge = new Func<int>(() => { return 43; })
};
Does anyone have a real life situation where it would be necessary to define a function inside an anonymous type? Or is this just a result of the type inferencing with no practical application?
I would say it's more of a property of type Func<T>
rather then a method. In standard type declaration it would have this form:
private Func<decimal> myFunc;
public Func<decimal> MyFunc
{
get
{
return myFunc;
}
}
And the usage would be as of any function where you need to adjust your result dynamically to current values. Only with anonymous type you just group the data temporarily and do not really need to implement a new type to do that.
Like for example assume I'm looping through some servicePayments
collection and I want to get some payment and a value for total payment by customer. Here to calculate TotalPayedByCustomer
I can use Func
. I couldn't do it in any other type of property. Below some code for this hypothetical type.
var payment =
new
{
Gross = gross,
Tax = taxAmount,
Commission = commAmount,
TotalPayedByCustomer = new Func<decimal>(
() =>
{
var totalPayed = 0m;
foreach (var custPay in customerPayments)
{
if (custPay.Payed)
{
totalPayed += custPay.Amount;
}
}
return totalPayed;
}),
};
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