Dimitri C.
Dimitri C.

Reputation: 22496

How to document the "non-nullableness" of reference types in C#?

In C#, instances of reference types are passed to functions as a nullable pointer. Consider for example:

public void f(Class classInstanceRef)

In most cases, the function will expect a non-null pointer (in 95% of all cases in my experience). What is the best way to document the fact that this function expects a non-null pointer?

Update: thanks a lot for your responses so far!

Upvotes: 6

Views: 269

Answers (6)

Ruben Steins
Ruben Steins

Reputation: 2820

1) Make sure the method rejects any null

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

2) Add

/// <exception cref="T:System.ArgumentNullException"> is thrown 
/// when <paramref name="instanceRef"/> is <c>null</c></exception>

The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument (MSDN)

Upvotes: 16

Thomas Lundstr&#246;m
Thomas Lundstr&#246;m

Reputation: 1599

I'd do something like this:

/// <summary>
/// Does stuff
/// </summary>
/// <param name="classInstanceRef">some documentation</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="classInstanceRef"/> is null.</exception>
public void f(Class classInstanceRef)
{
  if (classInstanceRef == null)
    throw new ArgumentNullException("classInstanceRef");
}

Upvotes: 2

Massif
Massif

Reputation: 4433

if(classInstanceRef == null) { throw new NullReferenceException("classInstanceRef"); }

?

///<remarks>classInstanceRef cannot be null</remarks>

Upvotes: -1

Akselsson
Akselsson

Reputation: 790

Check out the code contracts library: http://research.microsoft.com/en-us/projects/contracts/

It enables you to specify pre-conditions to your code and have it verified using static analysis of the code-base:

Contract.Requires( x ! = null );

The library will be included in .NET Framework v 4 and there are commercial licenses for earlier versions of the framework.

Upvotes: 4

John Feminella
John Feminella

Reputation: 311586

In .NET 4, you will have the ability to use code contracts, which are meant for just this sort of thing:

Contract.Requires(classInstanceRef != null);

In the meantime, I think proper documentation and throwing an ArgumentNullException is acceptable.

Upvotes: 18

Ed Guiness
Ed Guiness

Reputation: 35267

Debug.Assert(classInstanceRef != null);

Upvotes: 3

Related Questions