#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 comment