Why CodeContracts Static Analyzer doesn't make warnings?

257 Views Asked by At

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)

4

There are 4 best solutions below

0
On

"How can I get notified of errors like this?": Resharper will warn you in that case.

Code contracts will warn you that the object might be null if there is a "Requires" that the object be non-null. You're asking for an implicit "Requires" for an object dereference, which seems reasonable on the face of it, but which CC for whatever reason doesn't seem to provide.

The documentation at http://msdn.microsoft.com/en-us/library/dd264808.aspx says that it does enforce such an implicit contract. I'm looking into it further.

RedHat beat me to it. More detail: You should check the "Implicit Non-Null Obligations" box under "Static Checking" in the Code Contracts tab of your project properties.

1
On

In properties page of your project on Code Analysis tab you can change Rules.

0
On

You should enable "Implicit Non-Null obligations" in the static analyzer options (Project Options|Code Analysis).

0
On

I had a similar problem. I had to turn up the warning level slider on the same panel as the "Implicit Non-Null obligations" checkbox.