0

Recently I learned you can check if a value is null when setting the value for a SqlParameter and if it's null set is a null. This was using the null-coalescing operator ?? which is very straight forward:

cmd.Parameters.Add(new SqlParameter("ID", ID.Text ?? (object)DBNull.Value);

Now can anyone explain this next example in more detail? Obviously, it's checking the string to see if it's empty but how does everything after the ? operator work? Also what are the difference between ?? and ? when it comes to performance?

cmd.Parameters.Add(new SqlParameter("ID", ID.Text == "" ? (object)DBNull.Value : ID.Text));
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SgtOVERKILL
  • 309
  • 3
  • 11
  • 1
    Note that `ID.Text ??` will often do nothing if `ID` is a control (since most controls will return `""` rather than `null`). – mjwills Nov 26 '18 at 22:38
  • 1
    Also, I'd suggest reading up on `string.IsNullOrEmpty`. – mjwills Nov 26 '18 at 22:39
  • 1
    I'm voting to close this question as off-topic because it's a 'help me read the manual' question – Chris F Carroll Nov 26 '18 at 23:05
  • @mjwills `ID` was a textbox that often times return `""` and inserted in my db rather than null. Also yes, I could use `string.IsNullOrEmpty`. I just didn't think of it, was focused on the right side of the operation. – SgtOVERKILL Nov 27 '18 at 13:12

1 Answers1

0

They are two different functions, one is for null coalescing while the other is acting as a conditional operator for a ternary function. The Microsoft Developer Network explains the two as follows.

Null-coalescing Operator This operator has higher precedence than the next section and lower precedence than the previous section.

x ?? y – returns x if it is non-null; otherwise, returns y.


Conditional Operator This operator has higher precedence than the next section and lower precedence than the previous section.

t ? x : y – if test t evaluates to true, then evaluate and return x; otherwise, evaluate and return y.

Greg
  • 11,302
  • 2
  • 48
  • 79
  • 1
    Clear easy explanation thank you. This may also help future viewers. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator Just so happens I finally found it after I asked this. – SgtOVERKILL Nov 26 '18 at 21:56