Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, should one check references passed to methods against null?

Well, a few months ago I asked a similar question about C and C++, but I've been paying more attention to C# lately due to the whole "Windows Phone" thing.

So, in C#, should one bother to check against NULL at method boundaries? I think this is different than in C and C++, because in C# one generally can determine whether a given reference is valid -- the compiler will prevent one from passing uninitialized references anywhere, and therefore the only remaining possible mistake is for it to be null. Furthermore, there's a specific exception defined inside the .NET Framework for these things, the ArgumentNullException, which seems to codify what programmers think they should be getting when an invalid null was passed.

My personal opinion is once again that a caller doing this is broken, and that said caller should have NREs thrown at them until the end of days. However, I'm much less sure about this than I am in native code land -- C# has quite a different programming style in places compared to either C or C++ in this regard.

So... should you check for null parameters in C# methods?

like image 899
Billy ONeal Avatar asked May 07 '11 04:05

Billy ONeal


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


2 Answers

Yes, check for them. Preferably use Code Contracts to tell the caller that you require non-null parameters

void Foo(Bar bar) {
    Contract.Requires(bar != null);
}

This is particularly advantageous since the client can see exactly what is required of parameters.

If you can't use Code Contracts, use a guard clause

void Foo(Bar bar) {
    Guard.Against<ArgumentNullException>(bar == null);
}

Fail fast.

like image 167
jason Avatar answered Oct 18 '22 11:10

jason


I think it's better to throw an ArgumentNullException (or use a contract as Jason suggests) if your method doesn't want a particular parameter to be null. It's a much better indicator by the contract to the client not to pass null in the first place when calling your method.

Null-checking is then the client's responsibility which makes for more maintainable code on both sides (often a win-win situation)... at least that's what I feel.

like image 35
BoltClock Avatar answered Oct 18 '22 12:10

BoltClock