I have this code (query is a string):
if ((query ?? "") == "")
return false;
Is that the same as
if (query == null)
return false;
What is the advantage of using ??
The null-coalescing operator (??) is useful when working with nullable
types---such as a nullable int (int?).
For example, you cannot do the following:
int? x = null;
int y = (int)x;
This code will compile, but at runtime, you'll get a
System.InvalidOperationException because you can't cast a null nullable
type to its equivalent non-nullable type.
To get around this, you'd want to use a default value, á la the null
coalescing operator:
int? x = null;
int y = x ?? 0;
This way, if x is null, you can return some reasonably sane default
when you are constrained to using something that isn't nullable.
In your code sample above:
if((query ?? "") == "")
return(false);
isn't the same as:
if(query == null)
return(false);
Because the comparison is different. It's actually identical to
code in TestValue() below:
public static bool TestValue(string val) {
if(val == null) return(false);
if(val == "") return(false);
// Assumed
return(true);
}
string x = null;
string y = "";
string z = "foo";
bool result;
result = TestValue(x);
result = TestValue(y);
The reason of course being that the string you're checking could be ""
already, and so you can't assume that query (in your code) was null if
it is "" after using ?? on it.
--- Mike