1

Possible Duplicate:
Static variables in C#

If you have a large function and in the middle somewhere you have a value that should be declared only the first time its encounter.

In c++ you can use static for this:

void func() {
  ...
  ...
  static double startPosition = 0.0;
  int var = startPositino - value;
  startPosition = var;
  ...
}

But in c# you cant have static variables inside a function, is there some other way to do this without declaring it outside the function?

Community
  • 1
  • 1
Merni
  • 2,842
  • 5
  • 36
  • 42
  • 1
    “If you have a large function” That's your problem right there. – svick Sep 06 '11 at 07:10
  • The question is not why c# does not allow static variables inside a function – Merni Sep 06 '11 at 07:13
  • Does it make a difference to you if it's a `private static` field? That's the best you can do in C#. – Jon Sep 06 '11 at 07:16
  • @Merni: The accepted answer at the linked question tells you that what you want is impossible. The closest "equivalent" to method statics are class statics. – In silico Sep 06 '11 at 07:44

1 Answers1

0
bool changed = true;



void func() // the large function from the question (it wasn't specified what it does or what is called)
{
   .....

   if(changed)
   {
       // here you initalize you variable (the static from the c++)
       changed = false;
   }

   .....
}
Flowz
  • 21
  • 3
  • Your code won't compile. What is the return type of `largeFunction()`? And how does it even relate to the question? – svick Sep 06 '11 at 07:19
  • The code sample does succeed in demonstrating the general concept of how this could be accomplished in C# - downvoting because it doesn't compile "out of the box" is pretty harsh. – MattDavey Sep 06 '11 at 08:04
  • I didn't donwnvote because of the compile error. But because the answer doesn't actually answer anything. It's just a code sample without any explanation an it's not obvious what does it have to do with the question. – svick Sep 06 '11 at 09:59
  • In your "large function" (as a hint: try to break your "large function" in smaller chunks of code ...multiple methods it would be easier) place a condition where: if the declared bool from the beggining is true ... initialize the variable. after that switch it to false and the variable will initialize only once – Flowz Sep 06 '11 at 11:06