#840 – Use an Anonymous Type as a Read-Only Subset of an Object

You often use anonymous types to store some subset of data from another object.  In many cases, you’re interested in only a subset of the properties present in the original object.  With an anonymous type, you get a new object containing only the properties that you care about.

In the example below, the dogInfo object declaration creates an anonymous type containing only two of the properties present in the Dog object that it is referring to.  These properties, as they exist in the new object, are read-only.

            Dog myDog = new Dog("Kirby", 15, "Balls balls balls", "Tennis ball",
                42.0, "Black");

            var dogInfo = new { myDog.Name, myDog.Age };

840-001

Advertisements