#833 – Some Examples of Anonymous Object Initializers

You create an anonymously-typed object using the object initializer syntax.  The declaration consists of a series of member declarators, each of which can be:

  • A named value (Name = value)
  • A value represented by a named object
            Dog myDog = new Dog("Kirby", 15);
            Dog otherDog = new Dog("Ruby", 3);

            var anon1 = new {Name = "Bob", Age = 49};
            var anon2 = new {DogName = myDog.Name, DogAge = myDog.Age};
            var anon3 = new {Name = "Pi", Value = Math.PI};
            var anon4 = new { Area = CalculateArea(2.0, 3.0) };
            int num = 42;
            var anon5 = new { FavoriteNumber = num, Name = "Arthur" };
            var anon6 = new { Dog = myDog, Owner = new Person("Billy") };
            var anon7 = new { FavNum = anon5, SomeGuy = anon1 };

            var anon8 = new {myDog.Name, myDog.Age};
            var anon9 = new { Math.PI, Math.E };
            string name = "Nelson";
            var anon10 = new { num, name };
            var anon11 = new { myDog, otherDog };
            var anonGroup = new { anon1, anon2, anon3 };

            var anon12 = new { Dog1 = myDog, name };
Advertisements

#653 – Projection Initializers

A projection initializer is a declaration for a member of an anonymous type that does not include a property name.

Here’s an example, where the members of the anonymous type are initialized using local variables.  The resulting property names in the anonymously-typed object match the variable names.

string title = "Seven Samurai";
string director = "Akira Kurosawa";
int year = 1956;

var movie = new { title, year, director };


You can also use properties of another object to initialize the anonymously-typed objects members.

            MovieInfo mi = new MovieInfo("Seven Samurai", "Akira Kurosawa", 1956);

            var movie = new { mi.Title, mi.Year, mi.Director };