Monday, January 7, 2008

C# : Extension Methods

For an example where you have a nullable value in the database and you represent this as a Nullable on your C# object (e.g., JoinDate). When you go to save this value back to the database, you want to save a DateTime value, otherwise you want to save a null to the database - specifically a DBNull.Value.

In C# 2.0 you'd have to write a static method like this:

public static class Util
{
public static object ToDBValue(Nullable nullable) where T : struct
{
if (nullable.HasValue)
{
return nullable.Value;
}
else
{
return DBNull.Value;
}
}
}
and use it like

db.SetParameterValue(cmd, Params.JoinDate, Util.ToDBValue( employee.JoinDate ));

In 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 class Util
{
public static object ToDBValue(this Nullable 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.JoinDate, employee.JoinDate.ToDBValue() );

Hope you like this!!! Share your thoughts with me !!!
- Rangoli