In VB.Net, I can declare a variable in a function as Static, like this:
Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex('&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)') data = badAmpersand.Replace(data, '&') ''// more processing return data End Function
Note that I need to use the keyword Static, rather than Shared, which is the normal way to express this in VB.Net. How can I do this in C#? I can’t find its equivalent.
Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this:
http://weblogs.asp.net/psteele/articles/7717.aspx
That article explains that it’s not really supported by the CLR, and the VB compiler creates a static (shared) variable ‘under the hood’ in the method’s class. To do the same in C#, I have to create the variable myself.
More than that, it uses the
Monitorclass to make sure the static member is thread-safe as well. Nice.As a side note: I’d expect to see this in C# sometime soon. The general tactic I’ve observed from MS is that it doesn’t like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.