Writing C# extensions

A few years ago a new code base was introduced in the .NET family called LINQ (Language Integrated Query). The possibility to do stuff with your object(s) using extensions. This is a real cool approach on easily adding possibilities to objects to make your code cleaner.

We all know how to make static methods in a class so we don't have to create an instance of a class in order to call the method like this:

Convert.ToInt32(string value)

But wouldn't it be easier by just extending the string with an method called "ToInt32" , so we can call it directly from the object itself?

"1".ToInt32();

As today, many libraries has these way of creating extensions. Like MVC, they created LabelExtensions class that extends HtmlHelper instances so we can easily create labels with the data of the htmlHelper without explicitly calling the class itself.

How do we do this?

Simply create a new class like this:

public class StringExtensions 
{
}

Then we specifiy the method.

public class StringExtensions 
{
    public static Int32 ToInt32(string value) 
    {
        return Convert.ToInt32(value);
    }
}

Now we cal call the method by using the class, but we are still not able to do it like an extension of the string itself. What we need to do is to tell the parameter that it needs to call from an instance by presetting it with "this", but the compiler wil complain that extension method cannot be defined in non-generic classes. So we tell the class that it is static.

public static class StringExtensions 
{
    public static Int32 ToInt32(this string value) 
    {
        return Convert.ToInt32(value);
    }
}

There you have it! Now you can call it directly from the object itself. Think of the possibilities that you have in this method you create. Maybe you can limit the string by 50 characters and return that but with checking the length of the string as well to prevent exceptions.

public static class StringExtensions 
{
    public static string Limit(this string value, int length = 50) 
    {
        if (value != null && value.Length > length)        
                return value.Substring(0, length);
        return value;
    }
}

By Stephan, Contributers: / 10/10/2013 / 2745 Views

Leave a reply