Fix "Possible System.InvalidOperationException" on Nullable

I had a C# method like:

------------------------
public void Blah (int? id)
{
     if (id == null) throw new ArgumentNullException ("id")

     DoSomething (id.Value);
}
------------------------

which doesn't display any R# warnings, but when I modified it to
------------------------
public void Blah (int? id)
{
     id.ThrowIfNull("id")

     DoSomething (id.Value);
}

public static class Extensions
{
      public static void ThrowIfNull (this Object self, String objName)
      {
          if (self == null) throw new ArgumentNullException (objName);
      }
}
------------------------

then the Possible System.InvalidOperationException warning is displayed.

How can I modify the ThrowIfNull method so that R# knows that i've already null-checked that variable?

2 comments
Comment actions Permalink

You'll need to decorate your method using the Code Annotations attributes, in particular the ContractAnnotationAttribute.

public static class Extensions
{
   [ContractAnnotation("self:null => halt")]
   public static void ThrowIfNull (this Object self, String objName)
   {
      if (self == null) throw new ArgumentNullException (objName);
   }
}

0
Comment actions Permalink

Thanks, that did the trick!

0

Please sign in to leave a comment.