Question

The following check is needed to check for null values. is there a way i can do it directly?

 if(node.ID==0)
 {
   cmd.Parameters["@ID"].Value = DBNull.Value;
 }
  else
  {
    cmd.Parameters["@ID"].Value = node.ID;
  }

is there way we can cicumvent this check and a design by which we can avoid this repetitive check for each value? (by the way its just a logic that 0 to be interpreted as NULL for my case but am asking the same about nullable objects like string too)

Was it helpful?

Solution 2

For nullable types, I'd just use an extension method:

public static object CoalesceNullToDBNull(this object input)
{
    return input == null ? DBNull.Value : input;
}

Then use it as:

cmd.Parameters["Foo"].Value = someExpression.CoalesceNullToDBNull();

(You could give it a shorter name, of course.)

That won't help for your case though, because you're trying to coalesce a non-null value to null. I would personally consider redesigning your model - use a nullable type for values which can be null, rather than using a magic number. However, you could still use a generic extension method:

public static object CoalesceDefaultToDBNull<T>(this T input)
{
    return EqualityComparer<T>.Default.Equals(input, default(T))
        ? DBNull.Value : (object) input;
}

That will convert 0, '\0', false, null etc to DBNull.Value. You'd have to use that with extreme care though, as I assume there are plenty of places where a 0 should really be a 0.

OTHER TIPS

You can use ?: Operator

cmd.Parameters["@ID"].Value = node.ID == 0 ? (object)DBNull.Value : node.ID;

If you are doing this regularly, try putting the check inside of a method.

For instance:

// ...
SetFormattedValue(ref cmd, node.ID);
// ...

private void SetFormattedValue(ref IDBCommand cmd, int id) // IDBCommand - or whatever your command type is
{
    if(node.ID==0)
    {
        cmd.Parameters["@ID"].Value = DBNull.Value;
    }
    else
    {
        cmd.Parameters["@ID"].Value = node.ID;
    }
}

You can use the ?? operator:

cmd.Parameters["@ID"].Value = node.ID ?? (object)DBNull.Value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top