For instance is it possible to write this
if (variable != null)
without using the operator != or == ?
For instance is it possible to write this
if (variable != null)
without using the operator != or == ?
How would you check if something is null if you do not want to use an operator ? What's the reason for this question anyway ?
Well, I'd just use ==
(if you are trying to avoid a custom equality operator, perhaps cast to object
- it will be a nop cast anyway)
Other than than, my money would go with object.ReferenceEquals(obj, null)
, but you could also use object.Equals(obj, null)
since it handles null
etc.
For completeness: why would I just use ==
/ !=
? Simple: the compiler can do this directly. The IL for a null-check against an object is actually:
That's it. Two IL instructions. It doesn't even do a "load null, equality check" - since the definition of "true" is "anything that isn't 0/null", and "false" is "0/null".
For something like ReferenceEquals
, that is:
I know which I prefer...
Call ToString() on it, if you get a System.NullReferenceException it was null. :-)
But why?
Well, the only other syntax that fits your description is to use the ?? operator, (which is still an operator, i gues...) but it either returns the value, or if the value is null, it returns the next expressions value as in
string nullStr = null;
string out1 = nullStr?? "NullString"; // out1 = "NullString";
// ------------------------------------------------------------
string realStr = "RealString";
string out2 = realStr ?? "NullString"; // out2 = "RealString";
You could really be a jerk and use:
if (x is object) {
// not null
}
else {
// null
}