Anonymous Objects or Types (.NET 3.0+ )

posted on Friday, December 26, 2008 12:53 PM

Details...

  • an anonymous type declaration begins with the new keyword followed by a member-initialzer list in braces {}
  • the compiler generates a new class definition that contains the properties specified in the new member-initializer list
  • all properties of an anonymous type are public and immutable
  • anonymous type properties are read-only (you cannot modify a properties value once the object is created)
  • each properties type is inferred from the values assigned to it
  • the compiler defines a ToString method that returns comma-separated list of property-name = value pairs
  • Equals method compares the properties of two or more anonymous types
  • Examples...

    //Create a 'person' object using an anonymous type
    var bob = new { Name = "Bob", Age = 37 };

    bob in this case is the anonymous type and the types of the properties are inferred by the value assigned.

    //display information (note here however that the ToString is not required as a ToString method is automatically defined and is the anonymous type)
    Console.WriteLine("Bob:" + bob.ToString());

    //the ToString() method would output the following
    Bob: { Name = Bob, Age = 37 }


    var steve = new { Name = "Steve", Age = 36 };

    //the compiler is able to recognize the anonymous type for bob and steve are identical and of the same class by the fact that the properties and types were identical for both bob and steve

    //the anonymous type also creates an equals method that is capable of comparing all objects of this anonymous type (so name and age properties will be compared)
    Console.WriteLine(bob.Equals(steve) ? "equal" : "not equal"));

    The output from the is "not equal".

    category: .NET Language Features

    Comments


    No comments posted yet.
    Post Comment
    Title *
    Name *
    Email
    Url
    Comment *
    Please add 7 and 2 and type the answer here:

    About Me

    An engineer by training and a software developer at heart. My techniques and approaches meld engineering approaches with software technology.

    Core to these principles is a systematic approach to the development of software with a strong lifecycle and process management emphasis through adoption of mature technologies.

    Ten years designing heavy structural steel and concrete structures and 12 years in the software development profession have embedded strong project management and business knowledge in my approaches.

    Subscribe to Rss Feed


    Follow me on twitter @dyardy