Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we add a method to an anonymous type that refers to the anonymous type's members? [duplicate]

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 = () => { }
};
like image 574
Shaun Luttin Avatar asked Jul 16 '14 01:07

Shaun Luttin


2 Answers

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.

like image 73
kemiller2002 Avatar answered Oct 12 '22 07:10

kemiller2002


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.

like image 31
Daniel Mann Avatar answered Oct 12 '22 06:10

Daniel Mann