I have several user controls, that are subscribed to the event handler in another class. I'm learning CodeContracts in C#, and I wonder, why does Static Analyzer allows writing code like this:
void MyUserControl_MouseEnter(object sender, MouseEventArgs e)
{
MyUserControl item = sender as MyUserControl;
item.DoSomething(); // I expect some warning here, because item can be null
sender.Equals(testObject); // This doesn't yield warning either
}
Here I have a potentially unsafe code, that can lead to null-reference exception.
I understand, that static analyzer probably cannot check, what will the actual type of sender
be. But in case it cannot prove it, I expect some warning, like CodeContracts: Possibly calling a method on a null reference
.
Or do I get some idea of contracts wrong? How can I get notified of errors like this?
UPD:
Yes, I did enable Implicit Non-Null Obligation
as it was suggested in the answers, but I still don't get a warning from Static Analyzer. Also I tried to run Code Analysis with Microsoft All Rules
rules set, also no warning. (But I'd prefer dealing with Code Contracts and perform some additional checks using Contract class, rather then with if-then-throw or something else)