473,761 Members | 4,421 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
Zytan <zy**********@y ahoo.comwrote:
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.
You can't do that for a local variable, but you can for a member
variable. I've never wanted to do it for a local variable - it's easy
enough to make sure that you never change it, because there shouldn't
be too much code to look through.

--
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 #21
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
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.

True, it would otherwise be impossible to access the shared (static) class-level variable, I
would have hoped the compiler to produce a warning as it's clearly not the intend of the
author of the method to declare a local as being shared (static )when it turns out it's not.
Note that even in this particular case, the compiler goes to a great lengths to protect the
variable during initialization, by generating some helper code which wraps the
initialization by a Monitor.Enter/Exit construct, really funny.

Willy.
Feb 28 '07 #22
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:u4******** ******@TK2MSFTN GP03.phx.gbl...
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
>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.


True, it would otherwise be impossible to access the shared (static) class-level variable,
I would have hoped the compiler to produce a warning as it's clearly not the intend of the
author of the method to declare a local as being shared (static )when it turns out it's
not.
Note that even in this particular case, the compiler goes to a great lengths to protect
the variable during initialization, by generating some helper code which wraps the
initialization by a Monitor.Enter/Exit construct, really funny.

Willy.
C++/CLI also supports local statics and follows the initialization behavior as imposed by
the C++ Standard, that means it's not thread safe.

Following class:
public ref class C
{
public:
C(){}
static void Foo()
{
static int i = 1;
}
};

Produces a static with global scope, irrespective the method's declaration (static or
other).

Willy.


Feb 28 '07 #23
True, visibility = lexical scope. What i really was trying to say was that the extend (or
lifetime) was different.
I think you mean "extent" :) I don't know why we all don't just use
'visible' and 'lifetime', rather than 'scope' and 'extent'.
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
Ok, so statics are allowed in VB, right.
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.
Right, I understand the difference between scope and extent.

AD = ?

Zytan

Feb 28 '07 #24
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.

You can't do that for a local variable, but you can for a member
variable. I've never wanted to do it for a local variable - it's easy
enough to make sure that you never change it, because there shouldn't
be too much code to look through.
Aaaah, and this is where you are doing the job that the compiler could
do. C# is robust and forces good programming, but this is one place
where VB and C# are lacking. I bet C# also disallows const parameters
like I frustrating found that VB doesn't have? I had a nice
discussion about this in the VB newsgroups.

So C# isn't so perfect after all. :)

I won't get into detail here, but the use of "const" offers many, many
wonderful features that people just don't know about until they use a
language that offers it, like C++. It's a godsend. You don't miss it
until you have it, and only then do you realize what it brings. I'll
find the link to the VB newsgroup thread if any wish to know about
them all.

Zytan

Feb 28 '07 #25
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** **************@ a75g2000cwd.goo glegroups.com.. .
>True, visibility = lexical scope. What i really was trying to say was that the extend (or
lifetime) was different.

I think you mean "extent" :) I don't know why we all don't just use
'visible' and 'lifetime', rather than 'scope' and 'extent'.
Right, extent.
Scope and visibility are most often used and this since a very long time in computer lanage
parlance.
A variables scope is most often related to it's lifetime, that is , how long that variable
exists in computers memory, most often the scope is the same as it's visibility, but there
are exceptions. That's why I said that in the case of a "local static" variable, that it's
"visibility " is not the same as it's scope, the variable doesn't cease to exist when it
leaves it's enclosing lexical scope.
Anyway, this is a can of worms I'm not going to open any further ;-)
>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

Ok, so statics are allowed in VB, right.
>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.

Right, I understand the difference between scope and extent.

AD = ?
Application Domain.

Willy.

Feb 28 '07 #26
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** *************@j 27g2000cwj.goog legroups.com...
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.

You can't do that for a local variable, but you can for a member
variable. I've never wanted to do it for a local variable - it's easy
enough to make sure that you never change it, because there shouldn't
be too much code to look through.

Aaaah, and this is where you are doing the job that the compiler could
do. C# is robust and forces good programming, but this is one place
where VB and C# are lacking. I bet C# also disallows const parameters
like I frustrating found that VB doesn't have? I had a nice
discussion about this in the VB newsgroups.

So C# isn't so perfect after all. :)

I won't get into detail here, but the use of "const" offers many, many
wonderful features that people just don't know about until they use a
language that offers it, like C++. It's a godsend. You don't miss it
until you have it, and only then do you realize what it brings. I'll
find the link to the VB newsgroup thread if any wish to know about
them all.

Don't forget that .NET (the CLI) is a multi language platform, imposing const correctness in
one language makes no sense if it's not enforced by all languages available for the
platform, more, it makes little sense if not enforced by the CLR.
Even C++ (the single language) doesn't enforce, const-correctness, it even provides a
facility to cast-away const.
Even if C# and VB were the only languages on .NET, it was simply not possible to enforce
const correctness, it's just too late unless MSFT is willing to re-write all FCL and as such
probably break all existing applications.
Willy.

Feb 28 '07 #27
Don't forget that .NET (the CLI) is a multi language platform, imposing const correctness in
one language makes no sense if it's not enforced by all languages available for the
platform, more, it makes little sense if not enforced by the CLR.
Yes, we got into that in the VB newsgroups. Perhaps that's why const
never made it in.
Even C++ (the single language) doesn't enforce, const-correctness, it even provides a
facility to cast-away const.
I discussed this, as well. No, you cannot cast away const. Not
directly. That's an important point.

Yes, it's possible to access and write over something that is const,
as you can with any language that lets you use pointers. So, it can
be 'cast-away' indirectly, but I don't think this should be called a
'cast', since it very much indirect.

The important distinction, as I went into detail in VB, is the
compiler checks that 'const' brings. The fact that it isn't a 100%
solution to prevention of variable changing is NOT why it is so
valuable.

It is valuable because, as most C# programmers should appreciate, for
the same reason that C# forces good programming ethics.
Even if C# and VB were the only languages on .NET, it was simply not possible to enforce
const correctness, it's just too late unless MSFT is willing to re-write all FCL and as such
probably break all existing applications.
It is unforunate given what it can bring to writing robust code. It
is also unfortunate that people who haven't experienced it cannot
truly appreciate it. It would fit 100% into C#'s design, and effort
to force good code.

I fear I am starting the same conversation I had a few weeks ago.

Zytan

Feb 28 '07 #28
On Feb 28, 3:31 pm, "Zytan" <zytanlith...@y ahoo.comwrote:
Don't forget that .NET (the CLI) is a multi language platform, imposing const correctness in
one language makes no sense if it's not enforced by all languages available for the
platform, more, it makes little sense if not enforced by the CLR.

Yes, we got into that in the VB newsgroups. Perhaps that's why const
never made it in.
Even C++ (the single language) doesn't enforce, const-correctness, it even provides a
facility to cast-away const.

I discussed this, as well. No, you cannot cast away const. Not
directly. That's an important point.

Yes, it's possible to access and write over something that is const,
as you can with any language that lets you use pointers. So, it can
be 'cast-away' indirectly, but I don't think this should be called a
'cast', since it very much indirect.

The important distinction, as I went into detail in VB, is the
compiler checks that 'const' brings. The fact that it isn't a 100%
solution to prevention of variable changing is NOT why it is so
valuable.

It is valuable because, as most C# programmers should appreciate, for
the same reason that C# forces good programming ethics.
Even if C# and VB were the only languages on .NET, it was simply not possible to enforce
const correctness, it's just too late unless MSFT is willing to re-write all FCL and as such
probably break all existing applications.

It is unforunate given what it can bring to writing robust code. It
is also unfortunate that people who haven't experienced it cannot
truly appreciate it. It would fit 100% into C#'s design, and effort
to force good code.

I fear I am starting the same conversation I had a few weeks ago.
This question came up at PDC'05, I believe, and if I recall the
response from the C# team was that const didn't make it into the
language because they were trying to figure out how to make it a 100%
solution, without providing the ability to cast it away, and without
ending up with the ugly cascading-cost problems that come up in C++
from time to time. Since they couldn't figure out how to do that, they
didn't include it in the language. Now it's probably too late. Too
bad, really.

Mar 1 '07 #29
On Wed, 28 Feb 2007 11:50:59 +0800, de************* @gmail.com
<de************ *@gmail.comwrot e:
>
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.
That's very true. Of course, it would be true of any data referenced by a
function that may be executed by multiple threads. I suppose one other
argument (in addition to the ones I mention in my other post) is that in
other cases, it should be more clear to the programmer that the use of the
data is not thread-safe, whereas a static local may not be readily
apparent to a programmer as not being thread-safe.

And of course, my proposed alternate solution (using a parameter to the
function rather than a static local) solves the thread safety problem, by
creating a new copy of the data for each iteration of the function (and
thus also for each thread).

Pete
Mar 1 '07 #30

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
9975
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
9909
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
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
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.