Bastien Vandamme
Bastien Vandamme

Reputation: 18485

In C# is it possible to evaluate if a variable is different of null without using an operator?

For instance is it possible to write this

if (variable != null)

without using the operator != or == ?

Upvotes: 1

Views: 284

Answers (6)

Marc Gravell
Marc Gravell

Reputation: 1062660

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...

Upvotes: 9

John Rasch
John Rasch

Reputation: 63435

You could really be a jerk and use:

if (x is object) {
    // not null
}
else {
    // null
}

Upvotes: 2

Charles Bretana
Charles Bretana

Reputation: 146469

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";

Upvotes: 0

Ian Mercer
Ian Mercer

Reputation: 39277

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

But why?

Upvotes: 2

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234424

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

Upvotes: 5

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

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 ?

Upvotes: 1

Related Questions