473,761 Members | 5,578 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
55 6244
Am Thu, 1 Mar 2007 19:54:38 +0100 schrieb Willy Denoyette [MVP]:
Please, I know the value 'static locals' could bring if I wouldn't have to deal with the
possible disadvantages, like lifetime management and thread safety.
Look at how both VB.NET and C++/CLI (both .NET language members) have implemented 'static
locals' and you'll see what I mean.
VB.NET stores the static in a per application domain heap, so here we know that the variable
goes away when the AD unloads, great, as long as you know that your AD was unloaded and the
"static locals" variables were initialized again.
In VB.NET, a static local is only static when declared in a static (shared in vb) method,
else it's simply a non static instance member, the same initialization protection code is
synthesized by the compiler for no visible reason (this is by design or it's a bug).
VB.NET protects the variable, so that it gets initialized correctly in the presence of
multiple threads, but, still you need to synchronize accesses whenever the function can be
called from multiple threads. This is quite confusing, who's consistently synchronizing
accesses to locals?
C++/CLI doesn't protect the initialization in a thread un-safe way (aka C++) .
C++/CLI stores the static in a process heap, here the variable's lifetime is that of the
process, EEK! this leaks memory when the AD unloads.
Now, what model would you want C# to follow? Whatever, there will always be a trade-off, and
you'll have to answer the question - does the advantage of static locals outweighs the
disadvantages?
Hello Willy,

tnx for that elaboration.

Of course, these are exactly the questions one has to answer when one wants
to implement the feature. My question is: why can't these questions be
answered the same way they have alredy been answered for statics at class
scope?

Isn't it simply a matter of confining the visibility of a - otherwise
"normal" static - to function scope? Memory layout, lifetime questions etc.
could remain unchanged.

Paule



Mar 2 '07 #51
Am Fri, 02 Mar 2007 14:16:30 +0800 schrieb Peter Duniho:
On Thu, 01 Mar 2007 23:57:53 +0800, Paul Werkowitz
<ne********@pri maprogramm.dewr ote:
>[...]
How could you ever assume that f will be called directly in f? My
original
example does not have such an assumption. To be honest: In a real world
application, f might call h, which might call g, which invokes a delegate
that sends a Windows-message which leads to another call of f

Fine. Then just put the "static" variable outside of the function, as
suggested elsewhere. At least that way, it is clear to anyone reading the
code where the data is stored and what its lifetime is.
Yes, that is possible. Whether it is good or better than local statics
needs to be seen. I just wanted to point out that passing another argument
often is not possible. If the situation is easy, you usualy don't need any
additional means to find th problem. In larger apps there are so many
functions... and suddenly f gets called again from a call within f.

Besides of that - even if it was possible, adding arguments to funtions
that don't use them and don't know nothing of them seems no good practice
to me. All of the functions simply would pass the argument to the functions
they call. The value does not have any meaning to them. It has only meaning
to f. I remember the day when we did not have exception handling. We passed
result state up to the calling function, and then again up to the next
level - until some caller handled them. Luckily this is not necessary any
more.

This all is only a nuisance - it clutters code and is unneccesary work, but
not really bad, only silly. But there are also severe conceptional
problems, too. For example, what happens if you want to use h yourself?
What do you tell your client to pass for that additional parameter? You
impose complexity on h and on all callers of h, although they have nothing
to do with the recursion problem of f. You sure know the principle of
locality, which is broken here.

(I know, you can write another overload of h without parameters and call
the modified h.... - yes, this moves the problems out of sight for h's
clients but the problems remain.)

>
>>See above. C# makes no such demand on you. It's true that it doesn't
allow for static local variables, but there are solutions other than
defining variables at the class level.

And these are?

Well, I proposed two, and others have provided additional methods. You
don't have to have a static local variable in order to track recursion
level.
You are right - but this is not the question. You always can use
alternative ways to accomplish something. I know a guy that keeps telling
me that Cobol is everything a serious programmer needs (no joke) - and,
he's right. Assembler would be equally possible.

It's not so much a question whether "there are alternative ways" but more
"what properties do these alternative ways have compared to local statics".
For example, I gave reason why additional parameters - as you suggested -
are not an option for me. I consider the disadvantages for my code as too
much. It it were possible at all.

[snip]
>
There is no "additional complexity". There is simply "different
complexity". How is keeping a static local variable, which you increment
upon function entry and decrement upon exit, not complex in and of
itself? Other solutions are not more complex...they are just different.
A valid argument. I answered in the paragraph above. For example. clients
of h have to deal with complexity which does not belong to their domain.
That kind of complexity I judge more severe that that of local statics.
What leaves the other solution that uses statics, too. Whether you use a
static at class scope or factor it out to another (static) class makes no
difference at all. For me, its not so much of a difference where that
static is located. The much bigger difference is that between instance and
static data. A programer simply *has* to understand the difference, period.
Yes, your kissin cousins are there...

>
>See the problem? The recursion-checking-value has absolutely no meaning
for h or anybody else except f. And thats why it should be confined to f.

But a static local variable isn't truly confined to f. The problem is
that it only *looks* like it is confined to f. The only confinement is in
visibility, and because it is not confined in other ways, it is possible
for a programmer to misunderstand what is going on and create bugs.
You probably mean initialization probs, and threading issues. Yes, the
unloading/relaoding of an AD re-initializes local statics in VB. Maybe they
sell it as a feature, IMHO its wrong.

What a programmer is interested in, is visibility. And no side effects, of
course. If local statics were implemented like class statics except
visibility, I canÄt see any problems.
>Could you please elaborate a little why use of static variables is bad
coding practice? I can't see this.

Well, for one in languages where a local static variable essentially
creates a global variable, you are violating the basic tenet to minimize
global variables. Global variables exist for the entire lifetime of an
application; even when they are not being used, they take up space.
Taking up space you aren't using is wasteful and is apoor programming
practice.
I don't agree with the tenet that globals are bad. Especially when movin
from C to C++ for example, they tend to be heavily overused. But it is as
with any language feature: its not the feature that is bad, it is the
improper use. Don't use globals when you don't have to - but use them when
its appropriate. Look at some arbitrary code and look for static classes
with data members.
Secondly, globals can be null, too. If space was an issue, you can
implement some lifetime management, e.g. with factories and managers. But
since an empty app uses 30 MB of memory on my machine, space mosty is not
an issue. And OS can swap out pages.

And, my local static simply is an int. When we talk about memory, the
additional parameter you suggest cost much more. Not to forget the
additional CPU load (of my dual core Intel).


>
Others have explained how in particular versions of VB, static local
variables have less-than-intuitive behavior. For example, the possibility
of a static local being reinitialized during execution.
Ack. Bad!
>
In C#, one problem your static local has is that if an exception occurs
within the routine, if there is no exception handler in that routine, then
the recursion level as tracked by your static local will be incorrect.
Alternatively, you have to add an exception handler in the routine, which
increases complexity (something you apparently are against).
Absolutely right. If exeption safety is an issue, more work is necessary.
Unfortunately .NET has no deterministic destruction, therefore we cannot
program janitors as elegantly as in C++, but one can use using-clause.
[parts snipped)
>
>But from a greater distance the picture is different.
Again, when you think you don't need local statics: please give a
suitable implementation of the recursion detection problem.

I suspect your definition of "suitable" will restrict possible examples to
those that behave in *exactly* the way a static local would. Given that,
I have to admit that it's unlikely anyone could come up with something you
consider "suitable". However, in reality you don't need something that
works *exactly* the way a static local would. You just need something
that solves the problem at hand (knowing how many levels of recursion
you've called the function), and there are a number of alternatives to a
static local in that case (as has already been pointed out). You
obviously disagree that they are "suitable", but so far you've made no
compelling argument that they are any worse than your proposed use of a
static local.
I hope you can agree that we must look at the advantages and disadvantages
of the alternatives. I have brought arguments that show the problems of the
sugested alternatives. You have brought your arguments why local statics
are no good. Everybody can make up his mind now.

((I have to go now, and hope I can write something to the rest of the
arrticle later))

Paule

Mar 2 '07 #52
I remember the day when we did not have exception handling. We passed
result state up to the calling function, and then again up to the next
level - until some caller handled them. Luckily this is not necessary any
more.
Some of us still do that. Exception handling can hide where code
direction can change (say, if you didn't know a function you called
could throw an exception). It's a valid argument, especially when
using libraries NOT designed from the ground up around OOP (say, C/C+
+, or VB6 or earlier).
This all is only a nuisance - it clutters code and is unneccesary work, but
not really bad, only silly.
Clutter, yes. Silly? not any more so than code branching even though
there's no explicit code telling it to do so (exception handling).
Each has their benefits. I think they are about equal, personally.

Zytan

Mar 2 '07 #53
Paul Werkowitz <ne********@pri maprogramm.dewr ote:

<snip>
What leaves the other solution that uses statics, too. Whether you use a
static at class scope or factor it out to another (static) class makes no
difference at all.
There is a *big* difference in terms of readability.

I can glance down the code of a class and ignore all methods, and thus
see all the state, both of the type and of any instances. That's not
true if state of the type/instance can be effectively hidden inside a
method.

--
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
Mar 2 '07 #54
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
Paul Werkowitz <ne********@pri maprogramm.dewr ote:

<snip>
>What leaves the other solution that uses statics, too. Whether you use a
static at class scope or factor it out to another (static) class makes no
difference at all.

There is a *big* difference in terms of readability.

I can glance down the code of a class and ignore all methods, and thus
see all the state, both of the type and of any instances. That's not
true if state of the type/instance can be effectively hidden inside a
method.
Agreed, the "static" in a method might attract your attention, however, like it's done in
VB.NET, where the static becomes instance state when declared in a non static method,
completely blurs readability.

Willy.

Mar 2 '07 #55
On Sat, 03 Mar 2007 00:26:27 +0800, Zytan <zy**********@y ahoo.comwrote:
I think I only ever used them for temporary debugging purposes (and
recursive counting like Paul mentioned), so I just miss my quick
debugging tool that I used to have. But, I'll get around it, I'm
sure.
Well, for "temporary debugging purposes", pretty much anything goes
anyway. In that case, there is even less validity in objecting to making
the static local a member within the class (static or otherwise, depending
on your needs).

Pete
Mar 3 '07 #56

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
4671
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
6367
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
4644
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
4675
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
3971
by: junw2000 | last post by:
When I define a static variable, where is the memory allocated for the static variable? Thanks. Jack
15
2783
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
9353
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
9788
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8794
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
7342
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...
0
6623
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5241
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3889
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3481
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2765
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.