Extension methods in 60 seconds
Extension methods enables you to hook up extra methods to an already existing (and possibly sealed) class, without the need of subclassing or changing the original class. Lets say I have a class from a third party vendor I use, which contains information on persons
public class Person
{
public string FirstName{ get; set;}
public string LastName{ get; set; }
//+++
}
However, I might have some situations where I like to generate a quick list of the full names of the persons. I could of course subclass Person and add the following method:
public string GetFullName()
{
return FirstName + " " + LastName;
}
But this would not be possible if the class was sealed like the String class in C#, and there might be other reasons why you don't want to subclass to add extra methods and functionality. In these cases, we could rather add the GetFullName method as an extension method to the Person class.
A couple of thing to do then:
- Create a static class to keep the extension method in a namespace called eg: Extensions
- Add the GetFullName method to this class
- Make the method static
- Add a parameter to the method "this Person person"
namespace ExtensionMethods
{
public static class TestingExtensionMethods
{
public static sting GetFullName(this Person person)
{
return person.FirstName + " " + person.LastName;
}
}
}
To use this extension method on our class operating on Person, we add "using ExtensionMethods;" and then we can use our method as if it was a "normal" method in the Person class:
using ExtensionMethods;
public class TestClass
{
public TestClass(Person person)
{
string fullName = person.GetFullName();
}
}
Linq contains many useful and often used extension methods which comes into play when we add using System.Linq directive, then eg IEnumerable suddenly supports GroupBy, OrderBy +++.
One final comment: Extension methods cannot access private methods in the class they extend!

Debugging an application hang or freeze
Code segments and syntax highlighting in Confluence
How to succeed with WPF and Silverlight (Slides
Converting from Blogger to WordPress
The is keyword: Yet another hidden treasure of
Why use Custom Control instead of User Control
Getting started with Caliburn Part 2: Multiple Views
A quick start guide to yield return and
Getting started with Caliburn
Troubleshooting Squeezebox network connections
March 11th, 2010 - 18:38
Testing anonomys comments on WordPress