Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all
i wanted to ask if it is possible to have a kind of variable in c# that behave like static local variable in c++,
I mean I want to have a local variable in a method, that it is assigned (initialize) just the first time the method invoked and after calling the method again and again it would not be initialize again and keep its value from the last time I invoked the method
thank you
Posted

What you are talking about is something like this:

C++
void SomeFunction(void)
{
   static int sVar = 1;

   ...
}


It is possible to do this in C and C++, but it is not possible in C#. Be aware that the C language is not object oriented and the C++ is a multi paradigm language.

The C# is a pure object oriented language and what you are trying to do break the principles of OOP: if you need a method to persist some state between calls, you should make that state variable a member of the class that contains the method.

Be aware that things that are possible with a programming language, could be not allowed by another language. And again, a coding style could be good with a language and bad with another.
 
Share this answer
 
Comments
cppwxwidgets 25-Aug-10 6:00am    
Brilliant, was a perfect answer, thanks alot
If you don't want it to change after initialization declare it static readonly. If you want to be able to change it later but have it retain the value between instances just mark it static.
 
Share this answer
 
v2
Comments
cppwxwidgets 25-Aug-10 4:10am    
when i say i want a local variable i don't mean Class level variable , I mean I want a method level variable and thanks for your suggestion about using Comment widgets
I want it to be local and in local scope we are not allowed to use static keyword at all, isn't it?
 
Share this answer
 
Comments
DaveyM69 25-Aug-10 4:04am    
That isn't an answer, it's a comment to my proposed answer therefore you should use the "Add Comment" widget below the post.
If you need class level scope, just create a class level variable.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900