Resharper 8 running in VS2010 is telling me I can remove a check for principal.Identity != null
:
I'm assuming this is because there's a NotNull attribute or something lurking in the code for IPrincipal, but it's quite easy to write your own IPrincipal implementation that returns a null Identity:
void Main() {
var foo = new FooPrincipal();
Console.WriteLine(foo.Identity == null ? "Yep!" : "Not Null");
}
class FooPrincipal : IPrincipal {
public IIdentity Identity { get; set; }
public bool IsInRole(string role) { return(false); }
public FooPrincipal() {}
}
How can Resharper know that the IPrincipal passed into this method isn't going to be one of my FooPrincipals that return null identities?
EDIT: Ok, here's a full reproduction case where Resharper actually encourages you to write code that blows up in production...
using System;
using System.Security.Principal;
namespace ResharperPrincipalTest {
class Program {
static void Main(string[] args) {
var p = new TestPrincipal();
var isJeff = IsUserCalledJeff(p);
Console.WriteLine(isJeff);
}
static bool IsUserCalledJeff(IPrincipal principal) {
if (principal != null) {
if (principal.Identity == null) throw(new Exception("Resharper says this will never happen!"));
return (principal.Identity.Name == "jeff");
}
return false;
}
}
class TestPrincipal : IPrincipal {
public bool IsInRole(string role) {
return (false);
}
public IIdentity Identity { get; set; }
}
}
and the screenshot from VS2010 showing Resharper's 'helpful' highlighting...
and sure enough, when you hit F5 the program throws an exception. I'd say that makes the answer to my original question "because Resharper is wrong" :)
EDIT 2: Resharper bug report filed at http://youtrack.jetbrains.com/issue/RSRP-398551