Sunday, September 25, 2011

C# Extension Methods

One of my favorite features in C# is Extension Methods. Let me explain why.

Did it ever happen to you that you needed to add a method to a class you cannot edit, and inheritance couldn't help as well?
This can happen in various opportunities, especially when working with libraries and SDKs that uses a certain class for its internal operations, and exposes this class to the user as well.

In such cases, in languages that doesn't support extension methods, the only way to add functionality to that class, is to write a "helper" class or method, and use it.

C# Provides a better way.
Let's say you have a blogging system, and you have a blog summary page, that displays only the first 100 characters of each post, as a teaser. There could be many ways to get the shortened text, but image you could have your own String class, that provides a method that displays the entire post if it's less than 100 characters long, and displays only the first 100 characters and "..." if it is longer.

Have a look at the following extension method:

public static class StringExtension
        public static String ShortenText(this String str, int length)
                if (str.Length > length)
                        return str.Substring(0, length) + "...";
                return str;

Simple. This code needs very little explanation. All it does is create a new extension method for the String class that implements the logic described above. Here's a sample usage for this new method:


The output of this would be "12345...", as you'd expect.

The possibilities of extending built-in classes provided by C# and the various libraries, such as ASP.NET MVC, are endless. Just make sure you don't abuse it.

The full source code of the sample given above is available on my bitbucket samples repository. It compiles on Mono as well as on MS C# compiler.

No comments:

Post a Comment