Posts Tagged ‘.Net4.0’

It’s been few days since I wrote anything as I was enjoying my christmas vecation 🙂 Hope you all had a wonderful holiday time celebrating christmas.

What I am going to share today is about using extension methods in .Net.I faced this scenario recently & thought will make a note of this so that months later I can look back & remember what I learnt. Extension methods are a special kind of static method that enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

For example if you are using LINQ to read a OracleDataReader & want to check if a column exists in a DataReader object,we do not have a direct method that does so.Here comes the use of a custom extension method.These are the steps to follow

  • Define a static class to contain the extension method.
  • The class must be visible to client.
  • Implement the extension method as a static method with at least the same visibility as the containing class.
  • The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
  • namespace Helper
    {

    public static class Extension
    {

    public static bool HasColumn(this IDataRecord dr, string columnName)
    {
    for (int i = 0; i < dr.FieldCount; i++)
    {
    if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
    return true;
    }
    return false;
    }
    }
    }

  • In the calling code, add a using directive to specify the namespace that contains the extension method class.
  • Call the methods as if they were instance methods on the type.
  • Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.

    public void Format(OracleDataReader reader)
    {
    try
    {
    bool iscolumnexist = reader.HasColumn(“Description”);

    }
    catch (Exception ex)
    {

    throw;
    }
    }

    Hope you find this code snippet useful 🙂

    Advertisements