473,761 Members | 2,455 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
Minor amendment to the other replies: C# does have one special case
of local statics, namely constants of value types.

int Func(int y) {
const int x = 5 * 6;
return x * y;
}

This function is legal. The C# compiler will precompute x and embed
it as a literal constant in the instruction stream.
--
http://www.kynosarges.de
Feb 28 '07 #11
Am Wed, 28 Feb 2007 09:34:50 +0100 schrieb Willy Denoyette [MVP]:
>>
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.
>
count has no function 'scope', it's a static after all, it has function 'visibility'.

Willy.
Hello Willy,
I did not claim that count has "function scope". In fact, I did not say
anything about the scope of count at all.

I said that count is interesting withing the scope of f only, which is a
different thing.

And, BTW, my question is still unanswered: How do you implement the given
task in C#?

(Of course I know the answer - but it is worse) Maybe someone can enlighten
me why local statics are not in the language.
Paule.
Feb 28 '07 #12
Am Wed, 28 Feb 2007 00:45:17 -0500 schrieb William Stacey [C# MVP]:
>| 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.
That's how you have to do it in C# (but not in other languages, e.g. C++).
In C# you have to write

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

// -- the internals of f

count--
}

static int count;

which, IMHO, is clearly inferior.

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.
If it's not appropriate, then simply don't use static locals. I gave an
example where it would be nice. Many other situations come to mind.

>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.
It would be a non-breaking change, and could have been added with V3. The
fact that nobody complains sheds some light on peoples mindsets. Of course
you can circumvent it - like nearly everything. If you hadn't local
variables at all, you could fix that in the same way, too.....

My 2 cents...
Paule
Feb 28 '07 #13
"Paul Werkowitz" <ne********@pri maprogramm.dewr ote in message
news:13******** *************** ******@40tude.n et...
Am Wed, 28 Feb 2007 09:34:50 +0100 schrieb Willy Denoyette [MVP]:
>>>
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.
>>
count has no function 'scope', it's a static after all, it has function 'visibility'.

Willy.

Hello Willy,
I did not claim that count has "function scope". In fact, I did not say
anything about the scope of count at all.
I said that count is interesting withing the scope of f only, which is a
different thing.
How is it different?
If this was possible in C#, like it is in VB.NET, then the scope would still be the scope of
a "static" in the CLR/IL, which is "Applicatio n Domain scope", the *visibility* however
could be that of f().
And, BTW, my question is still unanswered: How do you implement the given
task in C#?
You can't in C#, VB.NET allows you to "declare" a local static, but this is simply
syntactic sugar, the static still becomes a *type* variable (NOT an instance nor a local
variable) , and the compiler limits its *visibility* to the declaring function only.

(Of course I know the answer - but it is worse) Maybe someone can enlighten
me why local statics are not in the language.
Because the C# language designers did not see a great value in it?
Willy.

Feb 28 '07 #14
count has no function 'scope', it's a static after all, it has function 'visibility'.

I thought scope = visibility.

http://en.wikipedia.org/wiki/Variable#Scope_and_extent
"The scope of a variable is the portion of the program code for which
the variable's name has meaning and for which the variable is said to
be "visible"."

Zytan

Feb 28 '07 #15
Minor amendment to the other replies: C# does have one special case
of local statics, namely constants of value types.

int Func(int y) {
const int x = 5 * 6;
return x * y;

}

This function is legal. The C# compiler will precompute x and embed
it as a literal constant in the instruction stream.
I noticed that I can't do this:
const int x = MyMethod();
because MyMethod() isn't constant.

But, what I want to do is that after x is assigned, not allow it to
change. C# doesn't allow that. I wonder why.

Zytan
Feb 28 '07 #16
On Feb 28, 8:47 am, Paul Werkowitz <newsgro...@pri maprogramm.de>
wrote:
It would be a non-breaking change, and could have been added with V3. The
fact that nobody complains sheds some light on peoples mindsets. Of course
you can circumvent it - like nearly everything. If you hadn't local
variables at all, you could fix that in the same way, too.....
Oh, please. You cannot seriously compare the presence / absence of
local variables with the presence / lack of static variables local to
methods. They're not even in the same ballpark.

Here's a mindset for you: every feature that's added to C# has two
sides to it: the functionality / flexibility that it adds to the
language, and its potential for abuse. You yourself admit that this is
simply a "nice to have" that would make a few scenarios more elegant.
I agree with you.

The downside is the potential for abuse: the ability to create nasty
little functions that do something different "sometimes" because they
save state across calls.

For me, the question is not, "Why didn't they include this feature
that I would find useful?" but "Did they omit this feature because
it's not really all that useful and makes it easy to write junk code?"

C++ is an expert's language. It has many features that in an expert's
hands can result in more elegant code, but in the hands of a novice
become traps and pitfalls. C# is more workmanlike, IMHO. It's targeted
not at experts but at the average Joe Programmer, so the feature set
is different.

Feb 28 '07 #17
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** ************@m5 8g2000cwm.googl egroups.com...
>count has no function 'scope', it's a static after all, it has function 'visibility'.

I thought scope = visibility.

http://en.wikipedia.org/wiki/Variable#Scope_and_extent
"The scope of a variable is the portion of the program code for which
the variable's name has meaning and for which the variable is said to
be "visible"."

Zytan
True, visibility = lexical scope. What i really was trying to say was that the extend (or
lifetime) was different.
Consider this small sample in vb.net:

Public Class C
Public Sub Foo(item As Integer)
Static staticLocal As Integer = -1
staticLocal = item
End Sub
End Class

here "staticLoca l " is declared as a static local, that means that "staticLoca l " lexical
scope is equal to it's active binding in program code, that is from the beginning of Foo
till Foo returns, which is also it's visibility as far as Foo is concerned.
Now, the variable itself is a static (and really a type variable), as such has it's extend
(lifetime) bound to that of the containing AD on the CLR. It's starts life when the class
loads and ends when to AD unloads.

That why I said that it's scope did not equal it's visibility, but you are right I should
have been more explicit and used "extend" instead of "scope".

Willy.

Feb 28 '07 #18
Paul Werkowitz <ne********@pri maprogramm.dewr ote:
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.

That's how you have to do it in C# (but not in other languages, e.g. C++).
In C# you have to write

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

// -- the internals of f

count--
}

static int count;

which, IMHO, is clearly inferior.
On the contrary. It makes it clear that it's part of the state of the
type, without me having to read the *body* of a single method. The
state *will* end up as part of the state of a type or an instance (and
the fact that you used a static variable rather than an instance one
above is an interesting decision, btw) so why not make it obvious?
Then, if it clearly doesn't belong as part of the state of the
type/instance, that suggests the encapsulation is wrong and it should
be part of the state of a different type/instance.
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.

If it's not appropriate, then simply don't use static locals. I gave an
example where it would be nice. Many other situations come to mind.
Well, I can't say I've missed them coming from C/C++. If I need state
for the sake of recursion, I tend to pass that in the recursive method
call. That's cleaner, IMO, and doesn't leave any state around for
longer than it makes sense, unlike static local variables.
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.

It would be a non-breaking change, and could have been added with V3. The
fact that nobody complains sheds some light on peoples mindsets. Of course
you can circumvent it - like nearly everything. If you hadn't local
variables at all, you could fix that in the same way, too.....
I would personally be against the change, for the reasons above.

--
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 28 '07 #19
Willy Denoyette [MVP] <wi************ *@telenet.bewro te:
And, BTW, my question is still unanswered: How do you implement the given
task in C#?
>
You can't in C#, VB.NET allows you to "declare" a local static, but this is simply
syntactic sugar, the static still becomes a *type* variable (NOT an instance nor a local
variable)
I don't think that's quite right. If the Sub/Proc is a Shared one, it
becomes a "static variable" (C# terminology) but if it's not, it
becomes an "instance variable" (C# terminology). At least, that's what
my experimentation shows. Compile this as a DLL:

Public Class Foo

Public Sub First()
Static inFirst As Integer = 0
End Sub

Public Shared Sub Second ()
Static inSecond As Integer = 0
End Sub

End Class

The generated $STATIC$First$2 001$inFirst variable is an instance
variable, but $STATIC$Second$ 001$inSecond is a static variable.

--
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 28 '07 #20

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
9538
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
10123
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
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...
0
5384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3481
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.