#652 – Using Expressions and Variables in Anonymous Type Declarations

One way to declare an anonymous type is to specify the name of each property of the new type, along with the value of that property, expressed as a constant.

var movie = new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" };

When you declare an anonymously-typed object, you can use any expression as the value for a property.

// Note: GetFavMovie() returns a string
int birthYear = 1964;
var movie2 = new { Title = GetFavMovie(), Year = birthYear - 25, Director = movie.Director };

You can also leave off the named property and just include an named identifier representing a value.

        public static string Director { get; set; }
        private const int TheYear = 1956;

        static void Main()
        {
            string aMovieTitle = "Seven Samurai";
            Program.Director = "Akira Kurosawa";

            var movie2 = new { aMovieTitle, TheYear, Program.Director };
        }

The property names in the generated type will match the identifiers that you use.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #652 – Using Expressions and Variables in Anonymous Type Declarations

  1. I had no clue you could leave off the named properties. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: