0

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?

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting...I suspect this is the reason it was created, although perhaps it shouldn't have been placed in the System namespace. Thanks for the insight.
I agree... the NUnit version is extremely annoying. If you're using NUnit and Rhino together, it sucks having to fully qualify everything.
4

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.

Comments

4

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?

1 Comment

Ah, you're right, it isn't part of the base class library, it's part of a custom external assembly we have here. The method was implemented in a class called "Is" in the System namespace, which led to believe it was part of the BCL. Thanks for your help!
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.