morrog
morrog

Reputation: 714

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

Thank you.

Upvotes: 4

Views: 1272

Answers (4)

Philip Wallace
Philip Wallace

Reputation: 8015

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062492

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

Upvotes: 7

The Chairman
The Chairman

Reputation: 7187

The feature you're asking for is part of Spec#. This extension adds precondition, postcondition, and object invariant checking.

Upvotes: 3

Sani Huttunen
Sani Huttunen

Reputation: 24375

You'll need a third party plugin for something like that. Resharper can warn you about referencing nulls.

Upvotes: 4

Related Questions