13

Background: There is this developer principle "Should my function return null or throw an exception if the requested item does not exist?" that I wouldn't like to discuss here. I decided to throw an exception for all cases that have to return a value and this value only wouldn't exist in cases of an (programmatically or logically) invalid request.

And finally my question: Can I mark a function so that the compiler knows that it will never return null and warn anybody who checks if the return value is null?

MatthiasG
  • 4,434
  • 3
  • 27
  • 47
  • Possible duplicate of [How can I show that a method will never return null (Design by contract) in C#](http://stackoverflow.com/questions/484571/how-can-i-show-that-a-method-will-never-return-null-design-by-contract-in-c) – Simon P Stevens Dec 01 '10 at 12:55
  • Also: http://stackoverflow.com/questions/792531/c-how-to-implement-and-use-a-notnull-and-canbenull-attribute – Tamás Szelei Dec 01 '10 at 12:59
  • Oh, I didn't see them, although I was looking (obviously not hard enough) – MatthiasG Dec 01 '10 at 12:59

4 Answers4

9

You can do this using Code Contracts.

Example :

    public String Method1()
    { 
        Contract.Ensures(Contract.Result<String>() != null);

        // To do
    }
decyclone
  • 30,394
  • 6
  • 63
  • 80
  • Thank you, that seems to be what I'm looking for. An .NET out of the box solution would have been nicer but that seems to the usual way (looking at the number of advices for Code Contracts). – MatthiasG Dec 01 '10 at 13:03
  • 1
    At least it's out of the box on .NET 4 – Tim Robinson Dec 01 '10 at 13:10
  • 2
    Well, this is .Net out of the box solution. This is officially part of .Net 4.0. – decyclone Dec 01 '10 at 13:10
  • For those using later versions of .NET, Microsoft writes, "Code contracts aren't supported in .NET 5+ (including .NET Core versions). Consider using Nullable reference types instead." at [Code contracts (.NET Framework)](https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts). – Mike Grove aka Theophilus Mar 07 '22 at 14:55
3

Using Code Contracts you can define a contract that a method does not return null.

using System.Diagnostics.Contracts; // required namespace 

public T MethodName()
{
    Contract.Ensures(Contract.Result<T>() != null); //where T is the return type.

    // method body...
}
cspolton
  • 4,495
  • 4
  • 26
  • 34
2

You are looking for Code Contracts

Aliostad
  • 80,612
  • 21
  • 160
  • 208
0

If you return a value type, then it can't be null (unless you explicitly make it so using the system 'nullable' wrapper).

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153