#840 – Use an Anonymous Type as a Read-Only Subset of an Object
May 9, 2013 2 Comments
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 };
Unfortunately it’s not that useful because you can’t pass the anonymous type outside the current method, and you already have a reference to the original object anyway…
On the contrary, it could be quite useful. If you wanted to write a simple method that doesn’t need to pass output to anything else, you could do something like this:
private void WriteStuff()
{
var myDog = new { Name = “Jack”, Age = 5 };
var dog2 = new { Name = “Jill”, Age = 6 };
var collar = new { Type = “Plain”, Color = “Brown” };
var collar2 = new { Type = “Fancy”, Color = “Hot Pink” };
var dogsAndCollars = new []
{
new { DogName = myDog.Name, DogAge = myDog.Age, CollarType = collar.Type, CollarColor = collar.Color },
new { DogName = dog2.Name, DogAge = dog2.Age, CollarType = collar2.Type, CollarColor = collar2.Color }
};
foreach (var dogAndCollar in dogsAndCollars)
{
Console.WriteLine(“Dog Name: ” + dogAndCollar.DogName);
Console.WriteLine(“Dog Age: ” + dogAndCollar.DogAge);
Console.WriteLine(“Collar Type: ” + dogAndCollar.CollarType);
Console.WriteLine(“Collar Color: ” + dogAndCollar.CollarColor);
}
}
If you only ever needed any of the types “Dog”, “Collar”, or “Dog-and-Collar” within this method, then why create full-fledged classes for them? Why not take advantage of the free built-in anonymous types?