#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 };

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

One Response to #833 – Some Examples of Anonymous Object Initializers

  1. Pingback: Dew Drop – April 30, 2013 (#1,537) | Alvin Ashcraft's Morning Dew

Leave a comment