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!
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With