- Home /
Static variable inside a function like in C ?
In C lang I could do something like this:
void f()
{
static int a = 0;
printf("%d\n", a);
a++;
}
Calling this function 3 times would result in: 0 1 2
Is it possible to use static variables like this in C# ?
In other words, to make, somehow, a variable inside a function persistent, until the next call.
I know I could use global variables, but I would like to keep my code cleaner and less confusing.
Answer by tanoshimi · Nov 14, 2016 at 07:43 PM
There's no such thing as a global variable in C#, and nor is there a modifier to make local variables retain values between invocations (there is a C# static
modifier but that is for a totally different purpose).
But you can achieve what you describe with a member variable of the class:
public class ExampleClass
{
private int a = 0;
void f()
{
Debug.Log(a);
a++;
}
}
Answer by spraw · Nov 14, 2016 at 07:57 PM
There are no static function variables in C#.
As you've guessed already, you will have to use a class variable, static or not.
but I would like to keep my code cleaner and less confusing.
Functions/Methods shouldn't hold persistent data in my opinion. But to each their own.
If you are using Visual Studio you can use #region and #endregion to help make you code more organized, using region you can expand or collapse the region code.
Your answer
![](https://koobas.hobune.stream/wayback/20220612100656im_/https://answers.unity.com/themes/thub/images/avi.jpg)