C #: Force Checking For null With Compiler

I am developing an API, and some of the methods return null when they cannot perform the requested operation, for example, searching for an object by name. This requires that all of these methods check for null results or risk error.

Is there ever a compilation error / warning if the result of a method is not checked for null? For example, if you declare a variable and then use it without assigning anything, the compiler complains. Methods return link types, so Nullable does not work, although it does have the behavior I want.

Throwing an exception would also be a good solution, but as far as I know, C # has no way to force an exception to be caught, such as Java.

Thanks.

+4
source share
4 answers

You will need a third-party plugin for something similar. Resharper may warn you of references to zeros.

+4
source

IMO, these methods should throw an exception.

A lot of this could (theoretically) be improved in 4.0 using code contracts, as this makes it more formal when the method claims to return null (or not) and requires non-empty (or not).

But no; there is no built-in check for this; the compiler ensures that things are definitely assigned, but not what is assigned to them. In C # 3.0, you could do something sassy, ​​like:

public static T ThrowIfNull<T>(this T obj) where T : class { if(obj == null) throw new SomeException("message"); return obj; } 

Then you can use this as a free API:

 SomeReturnClass myObj = foo.SomeMethod().ThrowIfNull(); 

Then myObj will never be null ...

+7
source

The function you are requesting is part of Spe # . This extension adds a precondition, a postcondition, and verification of object invariants.

+3
source

Judging by other answers, at the moment this is not possible. Can a similar rule be added to StyleCop to provide a similar purpose?

See Creating Custom StyleCop Rules in C # for an example.

+1
source

All Articles