C# 3.0 Extension Methods - Real World Example

C# 3.0 Lambda Expressions play an integral part of making the LINQ framework work.  Outside of LINQ it is recommended that they be used sparingly because they are less "discoverable."  However, there are a couple of nice scenarios where extension methods have good potential to make your code more elegant as a stand-alone language enhancement.

Take an example where you have a nullable value in the database and you represent this as a Nullable on your C# object (e.g., EmploymentEndDate).  When you go to save this value back to the database, you want to save a DateTime value (if one exists), otherwise you want to save a null to the database - specifically a DBNull.Value.  With C# 2.0 you'd have to write a static method like this:

public static object ToDBValue<T>(Nullable<T> nullable) where T : struct  
{  
    if (nullable.HasValue)  
    {  
        return nullable.Value;   
    }  
    else  
    {  
        return DBNull.Value;  
    }  
}

and call it like this (note the line below is EntLib rather than straight ADO.NET but that's immaterial to this example):

db.SetParameterValue(cmd, Params.EmplEndDate, DBUtil.ToDBValue(person.EmploymentEndDate));

With C# 3.0 you can convert the static method to an extension method by simply adding the this modifier to the first parameter like this:

public static object ToDBValue<T>(this Nullable<T> nullable) where T : struct  
{  
    if (nullable.HasValue)  
    {  
        return nullable.Value;   
    }  
    else  
    {  
        return DBNull.Value;  
    }  
}

Which allows you to call the method like this:

db.SetParameterValue(cmd, Params.EmplEndDate, person.EmploymentEndDate.ToDBValue());

This syntax is much more intuitive and concise.

Tweet Post Share Update Email RSS