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:
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:
db.SetParameterValue(cmd, Params.JoinDate, employee.JoinDate.ToDBValue() );
Hope you like this!!! Share your thoughts with me !!!
- Rangoli
In C# 2.0 you'd have to write a static method like this:
and use it like
public static class Util
{
public static object ToDBValue(Nullable nullable) where T : struct
{
if (nullable.HasValue)
{
return nullable.Value;
}
else
{
return DBNull.Value;
}
}
}
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:
Which allows you to call the method 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;
}
}
}
db.SetParameterValue(cmd, Params.JoinDate, employee.JoinDate.ToDBValue() );
Hope you like this!!! Share your thoughts with me !!!
- Rangoli