How does R# recognize validation?

Typically in a method you would do something like this:

if(myParam == null)
    throw new ArgumentNullException();

Then you don't see the little squigglies from R# telling you that there is a possible null reference when you go to use the parameter later in the method.
However, for many reasons I have moved code like this into a resuable class library so I just do something like this:

Validate.IsNotNull(myParam).

This handles logging, etc and will throw an exception if it is null.  However, when I do this, R# gives me the squigglies when I use myParam later in my method.
Is there anything I can do to let R# know that the null check is being performed in that method?

Thanks

5 comments

Hello Michael,

You can mark your 'IsNotNull' method with 'AssertionMethodAttribute' from
ReSharper annotations. For more information see http://www.jetbrains.com/resharper/webhelp/Code_Analysis__External_Annotations.html.
Thank you!

Andrey Serebryansky
Senior Support Engineer
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"

Typically in a method you would do something like this:

if(myParam == null)
throw new ArgumentNullException();
Then you don't see the little squigglies from R# telling you that
there is a possible null reference when you go to use the parameter
later in the method.

However, for many reasons I have moved code like this into a resuable
class library so I just do something like this:

Validate.IsNotNull(myParam).

This handles logging, etc and will throw an exception if it is null.
However, when I do this, R# gives me the squigglies when I use myParam
later in my method.

Is there anything I can do to let R# know that the null check is being
performed in that method?

Thanks

---
Original message URL:
http://devnet.jetbrains.net/message/5317906#5317906



0

Thanks Andrey.  Do you have an example for something like this?

public void DoSomething(object o)
{
               Validate.IsNotNull(o);
               string a = o.ToString();
}

 

public class Validate
{
     public static bool IsNotNull<T>(T obj) where T : class
     {
          if (obj == null)
               throw new Exception();
 
          return true;
     }
}
0

Hi

This is what we use.

/// <exception cref="System.ArgumentNullException">value ist NULL</exception>
[DebuggerStepThrough]
[AssertionMethod]
public static void NotNull<T>([AssertionCondition(AssertionConditionType.IsNotNull)]T value, [Localizable(false)] string parameterName) where T : class {
     if (value == null) {
          throw new ArgumentNullException(parameterName);
     }
}



Kind regards,
Sven

0

If you're using the method to validate the arguments of a public method, it might be a good idea to add an [InvokerParameterName] attribute to your parameterName parameter. That way, R# will warn you if the parameterName doesn't match the name of a parameter.

0

Please sign in to leave a comment.