The code examples are not meant to work. They are meant to illustrate ways that I have tried to do what I think may be possible.
// Error: The name First does not exist...
var Contact = new
{
First = "",
Last = "",
FullName = First + " " + Last
};
// Error: Cannot assign lambda expression to anonymous type property
var Contact = new
{
First = "",
Last = "",
FullName = () => { }
};
Visual Studio 2013:
Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.
Actually yes you can: MSDN Documentation:
var fName = "First Name";
var lName = "Last Name";
var t = new
{
FirstName = "First Name",
LastName = "Last Name",
FullName = new Func<string>(() => { return fName + lName; })
};
Depending on how badly you want TypeSafety, you could do something like this also:
dynamic v = new ExpandoObject();
v.FirstName = "FName";
v.LastName = "LName";
v.FullName = new Func<string>(() => { return v.FirstName + " " + v.LastName; });
Although honestly, I would probably just create a nested type in the method's parent class with those properties and method. Either would work, and the internal class wouldn't messy up the rest of the project if it's only used in there.
No, you can't.
The reason is that anonymous types are intended to be transient so that you can deal with the results of projections in a concise manner, without having to create an explicit type to hold the results of transforming and projecting a set of data.
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