C#: Force Checking For null With Compiler
I am designing an API, and some of the methods return null when they cannot complete the requested operation, like searching for an object by name. This requires all usage of these methods to check for null results, or risk exposing a bug.
Is there anyway to have a Compile-Time error/warning if the result from a method is not checked for null? For example, if you declare a variable and then use it without assigning anything, the compiler complains. The methods return Reference Types and so Nullable would 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# does not have a way to force catching an exce开发者_JAVA百科ption like Java.
Thank you.
IMO, those methods should be throwing an exception.
A lot of this could (in theory) be improved in 4.0 with code-contracts, since that makes it a bit more formal when a method claims to return null (or not) and demand non-null (or not).
But no; there is no inbuilt checking for this; the compiler enforces that things are definitely assigned, but not what they are assigned to. In C# 3.0 you could perhaps do something cheeky like:
public static T ThrowIfNull<T>(this T obj) where T : class {
if(obj == null) throw new SomeException("message");
return obj;
}
Then you could use this as a fluent API:
SomeReturnClass myObj = foo.SomeMethod().ThrowIfNull();
Then myObj
will never be null...
You'll need a third party plugin for something like that. Resharper can warn you about referencing nulls.
The feature you're asking for is part of Spec#. This extension adds precondition, postcondition, and object invariant checking.
Judging by the other answers, this is not really possible at the moment. Could a custom rule added to StyleCop provide a similar purpose?
See Creating Custom StyleCop Rules in C# for an example.
精彩评论