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#?
In C you do not have the this keyword. Only in C++ and in a class, so your code is C and you use your this variable as a local method parameter, where you access the array struct.
In the C programming language, there are 32 keywords. All the 32 keywords have their meaning which is already known to the compiler.
Keywords are words that have special meaning to the C compiler. In translation phases 7 and 8, an identifier can't have the same spelling and case as a C keyword. For more information, see translation phases in the Preprocessor Reference. For more information on identifiers, see Identifiers.
In C programming , main is not considered as a keyword as main is predeclared and but not defined beforehand. The class does not have to be instantiate , the method could be called by the runtime as it is static and public.
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:
public Func<int> GetCounter()
{
int count = 0;
return () => count++;
}
Now you can use:
Func<int> counter = GetCounter();
Console.WriteLine(counter()); // Prints 0
Console.WriteLine(counter()); // Prints 1
Console.WriteLine(counter()); // Prints 2
Console.WriteLine(counter()); // Prints 3
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.
You'd have to create a static or instance member variable of the class the method is in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With