Why CodeContracts Static Analyzer doesn't make warnings?

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)


您应该在静态分析器选项(项目选项|代码分析)中启用“隐式非空义务”。


"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.


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.

链接地址: http://www.djcxy.com/p/23740.html

上一篇: 代码合同可以取代参数验证吗?

下一篇: 为什么CodeContracts静态分析器不会发出警告?