C # functions with static data

In VB.Net, I can declare a variable in a Static function, for example:

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 Static keyword, not Shared , which is the normal way to express this in VB.Net. How to do it in C #? I can not find its equivalent.

+6
source share
4 answers

Ha! Having posted the question, I found the answer! Instead of searching in C #, I had to find information on how VB.Net implements it, and typing the question that seems obvious to me. After applying this understanding, I found the following:
http://weblogs.asp.net/psteele/articles/7717.aspx

This article explains that this is not supported by the CLR, and the VB compiler creates a static (generic) variable "under the hood" in the method class. To do the same in C #, I have to create a variable myself.

Moreover, it uses the Monitor class to ensure that the static member is also thread safe. Nice.

As a side note: I expect to see this in C # soon. The general tactic that I observed from MS is that VB.Net and C # do not like too far apart. If one language has a function that is not supported by another, it usually becomes a priority for the language command for the next version.

+13
source share

Personally, I'm glad C # doesn't have that. Logically, methods have no state: types and instances. C # makes this logical model clearer, IMO.

+6
source share

Unfortunately, there is no equivalent in C #.

You will need a class level variable.

This is one of the few things that VB has that I would like to have C #.

+4
source share

You must declare this at the class level:

 private static readonly RegEx badAmpersand = new RegEx("..."); 
+1
source share

All Articles