0

In Java it is possible to annotate methods with annotations that allow some processor to infer nullity and give you a warning/compiler error if you'd violate the nullity contract:

@NotNull    
public String returnSomething() {
    return null; // would give a warning as you violate the contract.
}

// at call site
if (returnSomething() != null) { // would give you a warning about unneccessary if
}

public int doSomethingElse(@NotNull String arg1, @Nullable String arg2) {
    return arg1.length() + arg2.length(); // would give you a warning about potential NPE when accessing arg2 without a check
}

// at call site
doSomethingElse(null, null); // would give you a warning about violating contract for arg1

Is there something similar available for C#?

Jan Thomä
  • 13,296
  • 6
  • 55
  • 83
  • 2
    Have you looked into [Code Contracts](http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx)? – Yurii Jul 28 '14 at 05:53
  • Hi Yuriy, I have, though I was hoping for a less verbose approach. Also I see no really neat way with Conde Contracts to specify that a return value can be potentially null. – Jan Thomä Jul 28 '14 at 06:06
  • 1
    @JanThomä That's because that's the default. If you don't specify any promises for the result, then code must assume the method may return `null`. –  Jul 28 '14 at 12:52
  • @hvd shouldn't the compiler issue a warning then, when I try to use a potentially null return value without a previous if check? – Jan Thomä Jul 28 '14 at 12:55
  • @JanThomä It does, assuming Code Contracts is installed, static checking is enabled, and the warning level is suitably high. –  Jul 28 '14 at 13:13

1 Answers1

1

1) You can use Fody's NullGuard. It works at compile time (generates appropriate IL code):

public class Sample
{
    public void SomeMethod(string arg)
    {
        // throws ArgumentNullException if arg is null.
    }

    public void AnotherMethod([AllowNull] string arg)
    {
        // arg may be null here
    }

    [return: AllowNull]
    public string MethodAllowsNullReturnValue()
    {
        return null;
    }
}

When it gets compiled:

public class SampleOutput
{
    public void SomeMethod(string arg)
    {
        if (arg == null)
        {
            throw new ArgumentNullException("arg");
        }
    }

    public void AnotherMethod(string arg)
    {
    }

    public string MethodAllowsNullReturnValue()
    {
        return null;
    }
}

2) If you use ReSharper, you can use Contract Annotations.

Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50