static member declaration

  • Thread starter Thread starter Ben S. Terry
  • Start date Start date
B

Ben S. Terry

Can someone please tell me how to declare a static variable in a function?
The following generates a compiler error:

public class MyClass
{
public void MyFunc()
{
static int i; // Compiler error: Invalid expression term 'static'
}
}
 
You can't have a static variable inside a function, and I'm not sure I
understand why you would want one. You can place a static variable inside
the class, so the following class would work:

public class MyClass
{
static int i;
public void MyFunc()
{
//Do Something
}
}
 
public class MyClass
{
private static int myInt;

public MyClass()
{
myInt = 0;
}
}
 
Why doesn't CSharp allow static variables within the scope of a single
function? I realize that I can create a static variable within the class,
however I have a variable specific to only one function--why prohibit that?
 
Ben S. Terry said:
Why doesn't CSharp allow static variables within the scope of a single
function? I realize that I can create a static variable within the class,
however I have a variable specific to only one function--why prohibit that?

Because methods don't conceptually have state between invocations -
types and objects do.
 
Back
Top