views:

154

answers:

6

For instance is it possible to write this

if (variable != null)

without using the operator != or == ?

+1  A: 

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 ?

Frederik Gheysels
With a static method ? Staticclass.IsNull(variable)I would like to check if it's possible to write code without using operators.
Dran Dane
@Dran - but **why** do you want to write code without operators? Operators are (especially in this case) *faster*.
Marc Gravell
+5  A: 

You can use object.ReferenceEquals(variable, null).

Martinho Fernandes
... or by creating an extension method and calling it like `obj.IsNotNull()`
Mehrdad Afshari
+8  A: 

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:

  • load the ref
  • branch if true (or branch if false)

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:

  • load the ref
  • load the null
  • call the method
  • (which creates a stackframe)
  • load the first arg
  • load the second arg
  • do an equality check
  • (then passes the value back down the stack frame returning true/false)
  • branch if true (or branch if false)

I know which I prefer...

Marc Gravell
Marc, how do you know that? How do you know how much IL instructions is a C# statement? How can I learn it too?
Dran Dane
@Dran : Reflector. Plus I'm currently doing lots of meta-programming, so writing IL directly.
Marc Gravell
+2  A: 

Call ToString() on it, if you get a System.NullReferenceException it was null. :-)

But why?

Hightechrider
It works. I hope it was tongue in cheek though.
Martinho Fernandes
@Martinho - very much so!
Hightechrider
A: 

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";
Charles Bretana
+1  A: 

You could really be a jerk and use:

if (x is object) {
    // not null
}
else {
    // null
}
John Rasch
I didn't know `is` gave false for null. Thanks. Not that I'll use this code anywhere :)
Martinho Fernandes