Showing posts from January, 2008

Extension Methods in C# 3.0

The latest incarnations of the .NET languages include a slew of new features, and extension methods in C# is just one of them. Extension methods allow you to extend a class without subclassing it. You might be asking yourself "Why would I want to do that? Why not just subclass?" Well, what if the class you want to subclass is sealed, preventing you from subclassing it? Extension methods allow you to extend even sealed classes.

Let's say you have a class called Dog. Dog has all of the properties and methods of a real dog, including a Bark() method. Because of the strained relationship in the neighborhood between cats and dogs, you want your dogs to be able to meow to help further the cause of cat/dog co-existence. There's just one problem: the Dog class is sealed and can't be subclassed. The answer lies with extension methods.

First, create a static class. Extension methods must be part of a static class. Second, create a static member of the static cla…