473,732 Members | 1,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does C# have static local variables like C++?

I see that static is more restricted in C# than in C++. It appears
usable only on classes and methods, and data members, but cannot be
created within a method itself. Surely this is possible in C# in some
way? Or maybe no, because it is similar to a global variable (with its
scope restricted) which C# is dead against?

Zytan

Feb 27 '07 #1
55 6233
>Surely this is possible in C# in some way?
Nope, you have to make it a class member instead.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Feb 27 '07 #2
Zytan <zy**********@y ahoo.comwrote:
I see that static is more restricted in C# than in C++. It appears
usable only on classes and methods, and data members, but cannot be
created within a method itself. Surely this is possible in C# in some
way? Or maybe no, because it is similar to a global variable (with its
scope restricted) which C# is dead against?
No - methods only have "temporary" storage, and types/instances have
"longer term" storage. I've found that to lead to better encapsulation.
If you find methods which need state which isn't logically part of the
state of the object, you might consider moving the method to a
different class.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 27 '07 #3
Nope, you have to make it a class member instead.

Ok, thanks, Mattias

Zytan

Feb 27 '07 #4
No - methods only have "temporary" storage, and types/instances have
"longer term" storage. I've found that to lead to better encapsulation.
Yes, I can see that.
If you find methods which need state which isn't logically part of the
state of the object, you might consider moving the method to a
different class.
I was just using it for testing some code. In practice, I don't find
much use for static vars, but they are nice to throw something
together really quick. But i respect c#'s attempt to keep things
proper.

Zytan

Feb 27 '07 #5
Am Tue, 27 Feb 2007 20:52:54 -0000 schrieb Jon Skeet [C# MVP]:
Zytan <zy**********@y ahoo.comwrote:
>I see that static is more restricted in C# than in C++. It appears
usable only on classes and methods, and data members, but cannot be
created within a method itself. Surely this is possible in C# in some
way? Or maybe no, because it is similar to a global variable (with its
scope restricted) which C# is dead against?

No - methods only have "temporary" storage, and types/instances have
"longer term" storage. I've found that to lead to better encapsulation.
If you find methods which need state which isn't logically part of the
state of the object, you might consider moving the method to a
different class.
Now, how would you then write something like this in C#?

void f()
{
static int count;
if ( count 0 )
Debug.Writeline ( "recursion level" + count.ToString( ) );
count++;

// -- the internals of f

count--
}

IMHO, count is only interesting within the scope of f, and therefore should
be defined in f, and nowhere else. But C# forces me to define such
variables at class level, which is stupid.

(OK, its only a minor nuisance, and other things are much worse. But
sometimes I wonder how language designers come to their results).

My 2 cents...
Paule
Feb 28 '07 #6
Now, how would you then write something like this in C#?
>
void f()
{
static int count;
if ( count 0 )
Debug.Writeline ( "recursion level" + count.ToString( ) );
count++;

// -- the internals of f

count--
}

IMHO, count is only interesting within the scope of f, and therefore should
be defined in f, and nowhere else. But C# forces me to define such
variables at class level, which is stupid.
Paule, you raise an interesting point. Normally, I only need the
above for quick testing code, not for production code. So, maybe the
designers thought that anything needing a C++ static local variable is
bad. But, like you said, it's only visible inside the function. But,
of course, via pass by reference, anything can be made visible to
anything.

Certainly the fact that you must declare it at the class level is
WORSE than at the method level, I agree.

Zytan

Feb 28 '07 #7
On Feb 28, 5:18 am, Paul Werkowitz <newsgro...@pri maprogramm.de>
wrote:
Am Tue, 27 Feb 2007 20:52:54 -0000 schrieb Jon Skeet [C#MVP]:
Zytan <zytanlith...@y ahoo.comwrote:
I see that static is more restricted inC#than in C++. It appears
usable only on classes and methods, and data members, but cannot be
created within a method itself. Surely this is possible inC#in some
way? Or maybe no, because it is similar to a global variable (with its
scope restricted) whichC#is dead against?
No - methods only have "temporary" storage, and types/instances have
"longer term" storage. I've found that to lead to better encapsulation.
If you find methods which need state which isn't logically part of the
state of the object, you might consider moving the method to a
different class.

Now, how would you then write something like this inC#?

void f()
{
static int count;
if ( count 0 )
Debug.Writeline ( "recursion level" + count.ToString( ) );
count++;

// -- the internals of f

count--
}

IMHO, count is only interesting within the scope of f, and therefore should
be defined in f, and nowhere else. ButC#forces me to define such
variables at class level, which is stupid.

(OK, its only a minor nuisance, and other things are much worse. But
sometimes I wonder how language designers come to their results).

My 2 cents...
Paule
Some where I read (may be "FAQ in C++"), even in C++ this kind of
local static variable is not safe for multi threaded applications. So,
better use functionoid.
Debi

Feb 28 '07 #8
| Now, how would you then write something like this in C#?
|
| void f()
| {
| static int count;
| if ( count 0 )
| Debug.Writeline ( "recursion level" + count.ToString( ) );
| count++;
|
| // -- the internals of f
|
| count--
| }

IMO, if f() is not using any class state, then the method should probably be
a static anyway. In which case "count" would be a static member var.
Moreover, I normally find I end up wanting "count" in class scope anyway as
many times you end up wanting to enumerate it for debug, statistics, or
other flow control in other parts of the class. I have wrote and read lots
of classes, and I never really come up with much need for local static
scope. I can think of one time similar to above, but the fix is easy and
probably not worth the change to the language. However, if I had to bet, I
would guess they add it at some point.

--
William Stacey [C# MVP]
PCR concurrency library: www.codeplex.com/pcr
PSH Scripts Project www.codeplex.com/psobject

Feb 28 '07 #9
"Paul Werkowitz" <ne********@pri maprogramm.dewr ote in message
news:1i******** *************** ********@40tude .net...
Am Tue, 27 Feb 2007 20:52:54 -0000 schrieb Jon Skeet [C# MVP]:
>Zytan <zy**********@y ahoo.comwrote:
>>I see that static is more restricted in C# than in C++. It appears
usable only on classes and methods, and data members, but cannot be
created within a method itself. Surely this is possible in C# in some
way? Or maybe no, because it is similar to a global variable (with its
scope restricted) which C# is dead against?

No - methods only have "temporary" storage, and types/instances have
"longer term" storage. I've found that to lead to better encapsulation.
If you find methods which need state which isn't logically part of the
state of the object, you might consider moving the method to a
different class.

Now, how would you then write something like this in C#?

void f()
{
static int count;
if ( count 0 )
Debug.Writeline ( "recursion level" + count.ToString( ) );
count++;

// -- the internals of f

count--
}

IMHO, count is only interesting within the scope of f, and therefore should
be defined in f, and nowhere else. But C# forces me to define such
variables at class level, which is stupid.

(OK, its only a minor nuisance, and other things are much worse. But
sometimes I wonder how language designers come to their results).

My 2 cents...
Paule


count has no function 'scope', it's a static after all, it has function 'visibility'.

Willy.
Feb 28 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5395
by: IHateSuperman | last post by:
public class StaticField2{ public static void main(String args){ private int x, y; // <<== error 1 for ( y = 0 ; y < 100 ; y++){ x = StaticMethod(); System.out.println(" x = "+x); } } public static int StaticMethod(){ private static int m = 0; // <<== error 2
37
4657
by: Curt | last post by:
If this is the complete program (ie, the address of the const is never taken, only its value used) is it likely the compiler will allocate ram for constantA or constantB? Or simply substitute the values in (as would be required if I used the hideous, evil, much-abused #define :) ----------- const int constantA = 10; static const int constantB = 20;
2
6902
by: Steve | last post by:
Is a static method that uses local variables thread safe (eg in a web service) In the following code assuming GetRandomValue() and DoSomethingElse() are thread safe, is the static method thread safe public class Cach public static int GetAValue( int x = 0 x = GetRandomValue()
9
6364
by: Bryan Parkoff | last post by:
I have noticed that C programmers put static keyword beside global variable and global functions in C source codes. I believe that it is not necessary and it is not the practice in C++. Static keyword is useful inside struct, class, and function only unless you want to force local variable to be global variable so static is used. Do you have idea why most programmers do this? Bryan Parkoff
28
4633
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. Would the performance be better using Static versus Dynamic. I would think it would be quicker with STATIC declarations since the variables would only have to be created once. Can anyone confirm this. Thanks. -- Dennis in Houston
2
4672
by: plmanikandan | last post by:
Hi, I have a doubt of storing static variables in memory.I think static,global variables are stored in the same location.Static,Gloabal variables are stored in HEAP .Can anybody explain me the storage area of all type variable in memory Rgds, Mani
5
7132
by: WebMatrix | last post by:
Hello, It might seem like a stupid question to some. But I need to put this issue to rest once and for all, since it keeps coming up in code reviews every now and then. There’s a static function in business logic class invoked by a Web multi-user application. Each request calls this static function passing in one unique ID, and XML serialized object (as out param), function deserializes XML to object, creates new instances of DB Access...
6
3970
by: junw2000 | last post by:
When I define a static variable, where is the memory allocated for the static variable? Thanks. Jack
15
2782
by: Laser Lu | last post by:
I was often noted by Thread Safety declarations when I was reading .NET Framework Class Library documents in MSDN. The declaration is usually described as 'Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.' So, does this mean All the static/shared methods written in .NET compatible programming language, such as C#, VB.NET, are guaranteed to be...
0
8944
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8773
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9445
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9306
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9234
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6733
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2177
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.