Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Force Checking For null With Compiler

Tags:

c#

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 exception like Java.

Thank you.

like image 547
morrog Avatar asked Dec 08 '22 05:12

morrog


1 Answers

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...

like image 170
Marc Gravell Avatar answered Dec 26 '22 23:12

Marc Gravell