I have following two approaches for same functionality – one with “if” condition and one with “?? and casting”. Which approach is better? Why?
Code:
Int16? reportID2 = null;
//Other code
//Approach 1
if (reportID2 == null)
{
command.Parameters.AddWithValue("@report_type_code", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("@report_type_code", reportID2);
}
//Approach 2
command.Parameters.AddWithValue("@report_type_code", ((object) reportID2) ?? DBNull.Value);
UPDATE
Based on the answers, following are the benefits of ??
- Increased readability
- Decreased branching deapth of program flow (reduced cyclomatic complexity)
Note: Cost of casting as object is negligible.
REFERENCE
I always use null-coalescing operator in such cases:
etc.
It increases code readability, decreases branching depth. Also was created especially for database-related scenarios such as ADO.NET.