Quantcast
Channel: 2,000 Things You Should Know About C# » Anonymous Types
Viewing all articles
Browse latest Browse all 9

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

0
0

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


Filed under: Data Types Tagged: Anonymous Types, C#, Data Types

Viewing all articles
Browse latest Browse all 9

Latest Images

Trending Articles





Latest Images