Blogger Jeff = new Blogger

Programming and stuff in Western PA

C# 3.0 Extension Methods

C# 3.0 introduces a concept known as extension methods.  What these allow you to do is to "extend" static methods onto an existing instance class.  Trust me, it’s a lot easier to understand when seeing an example.  In mine, I’ll extend a FormatSSN method onto the string object :

class Program
{
    static void Main(string[] args)
    {
        String val = "987654321";
        Console.WriteLine(val.FormatSSN());
        Console.ReadLine();
    }
}

public static class Utilities
{
    public static String FormatSSN(this String input)
    {
        return String.Format("{0}-{1}-{2}", input.Substring(0, 3),
            input.Substring(3, 2), input.Substring(5, 4));
    }
}

Microsoft says "Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible."

So why would you ever want to use an extension method?  I would say for convenience purposes, like in the example above, perhaps you already have a pre-existing class and rather than go back and add a "FormatSSN" method, you could simply extend one to the current code base.

Tags: ,

Advertisements

December 1, 2007 - Posted by | .Net, C#

No comments yet.

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: