#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

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 #833 – Some Examples of Anonymous Object Initializers

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

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: