Tuesday, May 31, 2011

Anonymous Classes

.NET 3.5 or Greater

One of the nice features of the "var" keyword is that it lets you create Anonymous Classes.
Anonymous classes allow for a quick and easy way to define an object that has named properties within a method.

Creating an Anonymous class is this simple:
var person = new { Name = "Bob", Age = 47 };


Properties can be accessed just like a regular class.
MessageBox.Show("Name: " + person.Name);


A few things to keep in mind.
  • All properties are read-only -- once you set them, you can't change them.
  • You can't declare them outside of a method.
  • You can't really do much with them outside of the method that they're created in. Sure, you could pass them to another method as an Object, but once you do, there's no way to cast them back and use their properties (short of using reflection).

So in the end, they're intended to intended to be temporary and localized.

They work great with LINQ though.

List<string> animalNames = new List<string> { "dog", "cat", "horse", "meerkat" };

var animals =
(
from animalName in animalNames
select new { Name = animalName, Lengh = animalName.Length, Hash = animalName.GetHashCode() }
).ToList();

animals.ForEach(animal =>
{
MessageBox.Show("Name: " + animal.Name + "; Hash: " + animal.Hash);
}
);


So, there's a few things going on in the code above.
If you're not familiar with LINQ, I'm planning on making a series of tutorials on it in the near future (or you can check out the links at the bottom of this post). But the code above goes through all the strings in animalNames and makes a list of Anonymous Classes containing the Name, Length, and Hash.

(You'll note that var is also being used to hold the List<> of Anonymous Classes. There are a few other things you can do with var besides creating Anonymous Classes and this is one of them.)

After that, it loops through all the Anonymous Classes that were created and displays them in a MessageBox to the user.

http://www.beansoftware.com/ASP.NET-Tutorials/Linq-Objects-Collections-Arrays.aspx
http://www.blackwasp.co.uk/LinqToObjectsTutorial.aspx
http://www.developerfusion.com/article/8250/linq-to-objects-for-the-net-developer/

No comments:

Post a Comment