Reputation: 12051
Using dotnet 2.0. Can the following code be improved in style ?
private object GetObj_Version1(int? num)
{
return num ?? (object)DBNull.Value;
}
The cast looks a bit messy to me. Version2 below avoids the cast, but its long winded :
private object GetObj_Version2(int? num)
{
object numObj;
if (num.HasValue)
numObj = num.Value;
else
numObj = DBNull.Value;
return numObj;
}
Can you think of an alternative which is both short and avoids the cast ? TIA.
Upvotes: 2
Views: 155
Reputation: 1063884
The cast, in this case, does nothing at runtime - it is there purely for the compiler. If you really hate it, perhaps:
static readonly object NullObject = DBNull.Value;
private object GetObj_Version1(int? num)
{
return num ?? NullObject;
}
But I'd leave it myself. As an aside - since you are going to box it anyway, you could dispense with the overload, and just work with object
- then you don't even need the static
field:
private object GetObj_Version1(object value)
{
return value ?? DBNull.Value;
}
Upvotes: 6
Reputation: 21685
If you want to insert values to the database, then you can directly pass the nullable type as a procedure's parameter.
param.Add("@Param1", nullableParam);
Upvotes: 0