Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does there exist a keyword in C# that would make local variables persist across multiple calls?

Tags:

c#

c#-4.0

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#?

like image 911
merlin2011 Avatar asked Dec 14 '11 21:12

merlin2011


People also ask

Does this keyword exist 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.

Are there 32 keywords in C?

In the C programming language, there are 32 keywords. All the 32 keywords have their meaning which is already known to the compiler.

What are keywords in C programing?

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.

Why Main is not a keyword in C?

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.


2 Answers

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.

like image 123
Jon Skeet Avatar answered Sep 22 '22 21:09

Jon Skeet


You'd have to create a static or instance member variable of the class the method is in.

like image 24
George Duckett Avatar answered Sep 21 '22 21:09

George Duckett