Help on Conditional operator ?:

This works...

if(searchDate!=null) {
cmdP0.Parameters[
"@Medical"].Value=searchDate;
}
else{
cmdP0.Parameters[
"@Medical"].Value=DBNull.Value;
}

so why does the compiler not allow...

cmdP0.Parameters["@Medical"].Value = searchDate!=null searchDate:DBNull.Value;

------------------

I've been having trouble getting null values into my table when getting anything but text (eg ints & dates) from my textboxes

This code helped solved part of the problem

string inputDate = txtmDoLM.Text;
DateTime searchDate = null;
if(!string.IsNullOrEmpty(inputDate)) {
DateTime date;
if(DateTime.TryParse(inputDate , out date))
searchDate = date;
}
} I couldn't use DBNull.Value in place of null - this really is driving me mad.



Answer this question

Help on Conditional operator ?:

  • zort15

    Marcelo is quite right on providing the cast and is required in my sample as well.

    But an easier way to test for null is to use the Null Coalescing operator ( ). It basically says if my object on the left side is null, use the right which can be thought of as a default.

     string sDate = null;
    object myField;

    myField = (object) sDate DBNull.Value;

    Console.WriteLine(myField.GetType()); // System.DBNull



  • Timmy0614

    That's great, makes the code so much neater, and therefore hopefully quicker and easier to maintain.
  • R1ZWAN

    It does not work, because the second result (after the :) is of type DBNull and the first is of type DateTime. The tenary operator works only if both return types are the same!

  • ReneeC

    It would be helpful if you provide the error...

    but, off hand, you could try:
    cmdP0.Parameters["@Medical"].Value = (searchDate != null searchDate: DBNull.Value);

  • Wael Sayed

    Hi,

    Littleguru is right, the problem is that ternary operator in "cond a : b" only works if typeof(a) can be converted to typeof(b) or viceversa. It doesn't look for common types as in this case would have been object.

    Taking that into account you can "help" it by doing some casting like in:

    cmdP0.Parameters["@Medical"].Value = searchDate != null (object)searchDate : DBNull.Value;


  • Help on Conditional operator ?: