Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ReSharper telling me that "User.Identity == null" will always be false?

I have a simple property inside one of my ASP.NET MVC Controller classes.

enter image description here

I've seen this many times before, so understand what the message means, but usually it makes perfect sense. This, however, doesn't. To get to the underlined statement, User would have to NOT be null, so the check for User.Identity is fine.

The Identity property is part of the IPrincipal interface, and returns an object that inherits IIdentity.

To inherit this interface, or any interface for that matter, this property must be a reference type, and therefore can potentially be null, right?

So why is my beloved ReSharper moaning?

like image 885
Connell Avatar asked Oct 24 '12 16:10

Connell


1 Answers

You said you are using the GenericPrinciple as the implementation of IPrincipal. For this class, the Identity property can indeed never be null. It is easy to see if you look at the source code (e.g. using JetBrains dotPeek).

You can thank ReSharper's code annotations for the .NET framework class libraries for this.

In my ReSharper 6.1 annotations, there is this single code annotation related to this (in file ExternalAnnotations\mscorlib\mscorlib.4.0.0.0.Nullness.Generated.xml):

  <member name="M:System.Security.Principal.GenericPrincipal.#ctor(System.Security.Principal.IIdentity,System.String[])">
    <parameter name="identity">
      <attribute ctor="M:JetBrains.Annotations.NotNullAttribute.#ctor" />
    </parameter>
  </member>

This is just for the constructor though, I haven't found one for the Identity property. So either you are using a ReSharper version that has annotation for that property too or ReSharper is doing some additional analysis.

In any case, it is ReSharper being clever (and right!).

like image 199
bitbonk Avatar answered Nov 14 '22 22:11

bitbonk