开发者

Difference between Is.NotNull and != null

I have come across some code in a 开发者_高级运维few projects which use if(Is.NotNull(SomeObject)) instead of if(SomeObject != null). Is there any difference between the two methods? When would one use a particular method over the other, or is it just a style choice?


I've seen Is.Not.Null as part of NUnit, as well as Is.NotNull from Rhino.Mocks.

Generally the functionality is not going to be any different - the pupose of Is.NotNull is just to express your unit tests more "fluently", or naturally. There's been many a discussion about the readability of tests, and the idea behind a fluent syntax is that when you read it from left to right, it forms a sentence describing what the line of code is doing.


The Is type in your sample is not something I've seen before in the Base Class Library. It sounds like something written by someone at your company or elsewhere, perhaps as part of a "fluent" library.


There can be a subtle difference, if the compile time type of the SomeObject expression has overloaded !=. I would hope it wouldn't make any difference in the end though, assuming everything's been implemented sensibly.

It's hard to know exactly what's going on here though, as Is.NotNull isn't part of the Base Class Library as far as I'm aware... are these projects using some other utility library? Are these in unit tests, or production code?


Likely there is a difference. If SomeObject has an equals/not equals overload it may no be called for the same reason these two statements are different:

if(x == null) ...

-- or --

if(((object)x) == null) ...

The later will use reference equality, while the former might use an operator overload.


You may need to look at Is.NotNull() and see if it looks inside the object to determine if it has any values set, for example.

It may be that an object is considered null for more reasons than the object value actually being null (or not set). It may be that if some attributes are not set that must be set, then it will also be considered null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜