Search code examples
c#ternarynull-coalescing-operator

Null-coalesing or ternary operator prefernce?


cmd.Parameters.Add("p_Shift_Id", OracleDbType.Varchar2).Value = p_Shift_Id;

p_Shift_Id could be null. If it is null, then I want to use DBNull.Value. If it's not null, then the value that it contains.

What is the best approach? I would rather not use

 if(p_Shift_Id == null)
 {
     cmd.Parameters.Add("p_Shift_Id", OracleDbType.Varchar2).Value = DBNull.Value;
 } else {
     cmd.Parameters.Add("p_Shift_Id", OracleDbType.Varchar2).Value = p_Shift_Id;
 }

Solution

  • Cast p_Shift_Id as object and then use Null-Coalescing operator as follows:

    cmd.Parameters.Add("p_Shift_Id", OracleDbType.Varchar2).Value = (object)p_Shift_Id ?? DBNull.Value;