Tuesday, November 9, 2010

How To: Extension Methods with C#, definition and implementation of Extension Methods in code

We all know that there are many types in .Net Framework. Each type contains value, property(ies) and Methods. We can create derived types to use existing type properties and methods and add our own custom methods and properties. But in some cases we do not need to add any properties but only need to add some method which can be used, Extension Method provides a functionality with which we can create a method and use it with existing type and there is no need to create a derived type, isn’t it interesting?

In this article we will see how to define an Extension Method and how to use it. An Extension Method is static method to specially work with an existing type, but it will be called like it is part of original type. In coding there is not any difference between call of an y method defined in type or an Extension Method of the type.

As a type we can consider string, int, arrays of any type and even List, Collection or a DateTime can be treated as a type and we can create extension method for that.

First of all we will take example of string and create an extension method for it. Most of the time we need to check length of the string and then we need to remove extra characters beyond certain limit, lets create an extension method for it.

public static class StringExtension
    {
        public static string TrimToLength(this string objString, int Length)
        {
            return objString.Length > Length ? objString.Substring(0, Length) : objString;
        }
    }

In above example we have created a static class which will contains extension methods for string. And we have created a static method containing 2 arguments. Now first argument defines on which type the method will work and this argument is preceded with modifier this. Second argument and onwards if any will be arguments in the client calls. Method return types define what output our method will return. Now lets see how we will use above extension method in our code.

string s = "This is a dummy string";
Console.WriteLine(s.TrimToLength(100));
Console.WriteLine(s.TrimToLength(6));

Above implementation will generate output as below

This is a dummy string

This i

Lets take an example of DataReader. When we use data reader and we are retrieving data from various method we are using dataReader.GetString(dataReader.GetOrdinal("fieldName")) this method will raise error if the field value is null so we will modify our code to check the whether field is null or not with dataReader.IsDBNull(dataReader.GetOrdinal("fieldName")). Generally there are many fields and we need to check null for all of them. Lets see if we create extension method for it how much easily we can do for all of the fields.

public static class DataReaderExtension
{
    public static string GetStringOrDefault(this IDataReader dataReader, string fieldName)
    {
        return dataReader.IsDBNull(dataReader.GetOrdinal(fieldName)) 
            ? string.Empty 
            : dataReader.GetString(dataReader.GetOrdinal(fieldName));
    }
}

Implementation of the above method will be as below (dr is a SqlDataReader)

dr.GetStringOrDefault("fieldName1");
dr.GetStringOrDefault("fieldName2");
dr.GetStringOrDefault("fieldName3");

So you can see that we do not need to repeat our code of check of db null and get ordinal and we can directly use our single method.

We can create extension method for DateTime to calculate difference between date instance and current date. We can also create extension method with all the types which are inherited from System.Object.

 

Yours,

Nirav

del.icio.us Tags: ,