That is, in C, we can define a function like:
func(){
static int foo = 1;
foo++;
return foo;
}
and it will return a higher number every time it is called.
Is there an equivalent keyword in C#?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, there’s no such thing in C#. All state that you want to persist across multiple method calls has to be in fields, either instance or static.
Except… if you capture the variable in a lambda expression or something like that. For example:
Now you can use:
Now of course you’re only calling
GetCounter()once, but that “local variable” is certainly living on well beyond the lifetime you might have expected…That may or may not be any use to you – it depends on what you’re doing. But most of the time it really does make sense for an object to have its state in normal fields.