Is there an equivalent static C in C #?

In C, I can do

void foo() { static int c = 0; printf("%d,", c); c ++; } foo(); foo(); foo(); foo(); 

he should print 0,1,2,3

Is there an equivalent in C #?

+7
source share
5 answers

Something like:

 class C { private static int c = 0; public void foo() { Console.WriteLine(c); c++; } } 
+3
source

There is no way to achieve the same behavior as a function variable static c ...

+3
source

While some have suggested a static member variable, this is not the same because of visibility. As an alternative to aquinas answer, if the closure is accepted, then this can be done:

(Note that Foo is a property, not a method, and c is "per instance".)

 class F { public readonly Action Foo; public F () { int c = 0; // closured Foo = () => { Console.WriteLine(c); c++; }; } } var f = new F(); f.Foo(); // 0 f.Foo(); // 1 

However, C # does not have the direct equivalent of the static variable in C.

Happy coding.

+3
source

There are no global variables in C #, however you can create a static field in your class.

 public class Foo{ private static int c = 0; void Bar(){ Console.WriteLine(c++); } } 
+2
source

You cannot do this at the method level. The closest thing you can do at the method level is something like this, and it is not that close. In particular, it only works if you have a link to a counter. If someone else calls this method, they will not see your changes.

  class Program { static IEnumerable<int> Foo() { int c = 0; while (true) { c++; yield return c; } } static void Main(string[] args) { var x = Foo().GetEnumerator(); Console.WriteLine(x.Current); //0 x.MoveNext(); Console.WriteLine(x.Current); //1 x.MoveNext(); Console.WriteLine(x.Current); //2 Console.ReadLine(); } } 

Interestingly, VB.NET supports static local variables: http://weblogs.asp.net/psteele/pages/7717.aspx . As this page notes, .NET itself does not support this, but the VB.NET compiler fakes it by adding a static class variable.

+2
source

All Articles