ReSharper claims that my expression is always true? Is it correct or is it a bug?

1.6k Views Asked by At

ReSharper is claiming that my null check against serviceProvider is always true, which is odd. I figured that serviceProvider very well might be null. Am I wrong here, or is this a ReSharper bug?

public override object ProvideValue(IServiceProvider serviceProvider)
{
    switch (Mode)
    {
        case BindingMode.TwoWay:
            throw new InvalidOperationException("Invalid binding mode.");

        case BindingMode.OneWayToSource:
            throw new InvalidOperationException("Invalid binding mode.");

        case BindingMode.OneWay:
        case BindingMode.OneTime:
            break;

        case BindingMode.Default:
            if (serviceProvider != null) // Expression is always true?? O.o
            {
                // Returns something possibly...
            }

            throw new InvalidOperationException("Invalid binding mode.");

        default:
            throw new InvalidOperationException("Unexpected binding mode.");
    }

    return base.ProvideValue(serviceProvider);
}

Update:

I created a console application, and the following code gives a warning as well (from ReSharper) Possible null assignment to entity marked with 'NotNull' attribute.

var binding = new CustomBinding();
binding.ProvideValue(null);
2

There are 2 best solutions below

0
On BEST ANSWER

Taken from the documentation at http://msdn.microsoft.com/en-us/library/system.windows.markup.typeextension.providevalue%28v=vs.110%29.aspx

You can pass null for serviceProvider, but only if this TypeExtension instance was established with an initial true type in the constructor rather than a typeName. Otherwise, this markup extension implementation relies on services based on the passed serviceProvider. It must not be null. The serviceProvider is expected to provide a service for IXamlTypeResolver.

Also you can view When can a generic parameter never be null for more information about this.

Apparently, if i am correct, this method has a contract [NotNull] for its parameter because some implementations throw errors upon null arguments.

2
On

Since ProvideValue is a function that needs IServiceProvider Resharper correctly assumes that if the serviceProvider is null is being checked prior to calling the ProvideValue function thus the espression is always true