# Checking for null in delivery functions

In my Repository class:

public class DeliveryRepository : IDeliveryRepository
{
private readonly List<Delivery> deliveries = new List<Delivery>();

{
if (item == null)
{
throw new ArgumentNullException("item");
}
return item;
}
}


...I could implement my Add() method this way:

public Delivery Add(Delivery item)
{
Contract.Requires(item != null);
return item;
}


public Delivery Add(Delivery item)
{
Contract.Requires<ArgumentNullException>(item != null, "item");
return item;
}


Which of the three is best? Does it matter? Just a matter of style/preference?

Are they 2 of one, a pair of the other, and a couple of the third?

• I think it's preference and also what decisions your programming team has made in regards to the tools available. I personally like the second one, 3rd then first one however I've also never used the Contract features of .NET either (only read about them) – dreza Oct 11 '13 at 19:48

If you are addressing Code Contracts specifically then you should adopt a programming style that reinforces exception handling policy in release build, i.e. whether you require argument validation at runtime and whether Code Contracts will be part of release build or not.

I suggest taking a look at this diagram (copied from Code Contracts user documentation) and consult it with your team.

• It is really up to you, whichever preference you have. Otherwise the first two are the most commonly used examples. The first example checks to see if the "item" is null and if it is, then do something....., while the second one does the opposite. If the "item" is not null then do something..... This are common programming techniques used and applied to many coding problems.

• However you decide to solve the problem, should be well thought and should get the job done. In some cases; when you are attempting to solve a problem, the 1st example might be appealing. While in some other scenarios, the 2nd example might be appealing. So again it might depend on the problem you have to solve.