#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 };



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. 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?

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 )

Connecting to %s

%d bloggers like this: