Argument validation issue

I have a method which takes an XDocument argument. If either the document or its root element are null, I want to throw an ArgumentNullException. For clarity, I also want to decorate the argument with the [NotNull] annotation.

If I start with this:

public static Foo LoadFrom([NotNull] XDocument document)
{
    if (document == null || document.Root == null)
    {
        throw new ArgumentNullException(nameof(document));
    }
    
    ...

R# suggests I merge the sequential checks.

Once I do so:

public static Foo LoadFrom([NotNull] XDocument document)
{
    if (document?.Root == null)
    {
        throw new ArgumentNullException(nameof(document));
    }
    
    ...

R# warns me the the "conditional access qualifier expression is known to be not null". Which it would be, but only after the argument validation.

If I follow R# suggestion here, it will change the behaviour of my code - passing in null as the argument will produce a NullReferenceException, rather than an ArgumentNullException.

Looks like the null-checker exception for argument validation doesn't extend to the conditional access qualifier.

 

JetBrains ReSharper Ultimate 2017.1  Build 108.0.20170402.75312
ReSharper 2017.1.20170403.124732
Visual Studio Professional 2017 (version 15.0.26403.0)

1

Please sign in to leave a comment.