Reputation: 88
I have a C# function that is updating a database and need to check to make sure two values in a datarow are not null. I know that ValueA has a value more often than ValueB, so I have a check as follows to make sure I have the most efficient execution (note, using IsNull as a function to check both C# nulls and DBNull.Value):
var value= DataRow["ValueA"];
if (IsNull(value))
{
value= DataRow["ValueB"];
if (IsNull(value))
{
_log.LogError("Error occured while attempting to update a table...");
return;
}
}
Can anyone see a more efficient way to test whether both are null? Is there any way to reduce the number of lines of code but maintain the efficiency?
Upvotes: 1
Views: 152
Reputation: 2257
If you are using C# 7 or above you can use the null coalescing operator, like so:
var value = DataRow["ValueA"] ?? DataRow["ValueB"] ?? throw new Exception("Error occured while attempting to update a table...");
Combined with a Try...Catch
to catch the exception.
If the values involved are in fact DBNull
rather than actual null
, then you could do this instead (assuming they're int?
s):
var value = DataRow["ValueA"] as int? ?? DataRow["ValueB"] as int? ?? throw new Exception("Error occured while attempting to update a table...");
Upvotes: 3
Reputation: 4702
Ultimately you are making 2 null checks, regardless of the order you do them or how pretty your code is. When this is interpreted into IL the compiler will simplify this anyway, but in terms of humanly readable code this is fine. An alternative might be to not malloc value
to two different values and null check the values directly like:
if(IsNull(DataRow["ValueA"]) || IsNull(DataRow["ValueB"])
{
_log.LogError("Error occured while attempting to update a table...");
return;
}
Upvotes: 4