And another FxCop strange one

Here is the code:

Protected ReadOnly Property UserChapter() As String

Get

Dim dr As DataRow = Utilities.SharedData.drSyUse

Return dr.Item("chapter").ToString.Trim()

End Get

End Property ' GetUserChapter

 

And here is FxCop's complaint:

"file:///C:/Projects/AM.NET/CDS%20Forms/General/UIBase.vb<254>" (String)

Resolution : "UIBase.get_UserChapter():String declares a local, 'UserChapter',

of type System.String, which is never used or is only

assigned to. Use this local or remove it."

Help : "http://www.gotdotnet.com/team/fxcop/docs/rules.aspx?version=1.312&&url=/Performance/RemoveUnusedLocals.html"

 

These make no sense to me. 

 

 

4 Comments

  • Looks like the VB.NET compiler creates a local &quot;UserChapter&quot; variable so that the VB6-style of returning a value by setting a variable will still work. I.e. you could code this:



    UserChapter = dr.Item(&quot;chapter&quot;).ToString.Trim()



    And it would compile (and probably remove the FXCop warning). Also try compiling in release mode to see if it optmizes that out.

  • Patrick is exactly right. The compiler will emit a string local in order to hold the copy of the information returned from calling the ToString() on the object type, which is on the heap. Since you are returning a string, the compiler needs to emit a local string variable in order to get the string result and put it on the stack, and then the value type string is pulled back off the stack and returned.



    However, Patrick, assigning UserChaper the value of the ToString operation will not prevent the violation from occuring. The compiler will emit the same code whether you have the &quot;UserChapter = &quot; there or not. Also, debug versus release mode will have no impact on this.



    I think this is another one of those &quot;bugs&quot; that will be corrected in the next version so that FxCop doesn't report on compiler emited variables such as this.

  • And by the way, your code MIGHT (I know it does with datareaders) fail with an invalid cast exception if the value of that column in that row is null. You might want to check that.

  • This is a subtle rule - took me a few minutes to figure out what was going on when it happened to me.



    For class methods/properties like this, the compiler passes an implicit hidden &quot;Me&quot; parameter (&quot;this&quot; in C#). Because you don't do anything class-related in the method, this implicit parameter isn't needed. If you declare the property as &quot;Shared&quot; (&quot;static&quot; in C#), the compiler won't add the implicit parameter and FxCop will stop complaining about this problem.

Comments have been disabled for this content.