开发者

Difference between null == x and x == null? [duplicate]

开发者 https://www.devze.com 2023-03-27 06:53 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the difference between these (bCondition == NULL) and (NULL==bCondition)?

I have seen comparison开发者_如何学JAVAs done both ways. Is there a performance difference or is it just personal preference?

I saw it being used in this answer:

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)


In this case, its personal preference in C#.

Difference between null == x and x == null? [duplicate]

Yoda Conditionals


It's a rudiment from C++ days, where you could accidentally assign variable by using = instead of == and it would still pass the compiler cause you could pass almost anything into comparisons in C++. Do not use it in C#, cause it will not allow you to do so.

Valid C++:

if (p = NULL) // p gets assigned NULL and result is compared to 0

Invalid C#:

if (p = null) // can only use booleans in test


Using null == x prevents accidentally mistyping and missing out one equals symbol and therefore assigning rather than testing for a value. You would end up with null = x which would not compile.

In any case, using Object.ReferenceEquals(x, null) is probably better anyway, as it would prevent cases where == has been overloaded.


Absolutely identical in all aspects. Just a reversed way of doing the same thing.


Is there a performance difference or is it just personal preference?

No, absolutely no performance difference. It's only a matter of personal preference.

0

精彩评论

暂无评论...
验证码 换一张
取 消