Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 333
Dimitri C. Avatar asked Aug 24 '09 14:08

Dimitri C.


People also ask

Can we assign null to reference types?

A reference isn't supposed to be null. The compiler enforces rules that ensure it's safe to dereference these variables without first checking that it isn't null: The variable must be initialized to a non-null value. The variable can never be assigned the value null .

Why use nullable reference types?

Null reference types can help make your code more maintenance friendly and easier to spot bugs, as nulls can cause unexpected problems and application crashes. While nullable reference types aren't a panacea (as it is possible to ignore the warnings), they can help provide the compiler with extra information.

What is null forgiving operator?

The unary postfix ! operator is the null-forgiving, or null-suppression, operator. In an enabled nullable annotation context, you use the null-forgiving operator to declare that expression x of a reference type isn't null : x! . The unary prefix ! operator is the logical negation operator.


1 Answers

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.

like image 122
John Feminella Avatar answered Oct 20 '22 00:10

John Feminella