473,793 Members | 2,865 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Equivalent to C/C++ static variable in a function?

Back in the "old" C/C++ days, I used to declare static variables inside
functions. Something like...

// just a silly example to demonstrate the technique
int foo(void)
{
static int NextVal = 0;
NextVal = (++NextVal) % 317;
return (NextVal);
}

I use this technique/style for many varied things but basically this gave me
a quick and easy to maintain a value between function calls while limiting
the visibility of the variable.

I'm struggling to find a C# equivalent technique. The best equivalents I've
discovered so far:

1) If foo is a member function of class fred, create a private variable in
fred on which foo operates. This is *OK* but gives the variable whole class
scope when only one function NEEDS it. It would also seem to "clutter" the
class namespace unnecessarily.

2) Create a small foo class with just a get method. NextVal would be a
private variable inside the small foo class. This is also *OK* but setting
up a separate class just to appropriately scope a variable and maintain it
between calls seems overkill. I understand writing the class is not a huge
deal, but I'll be creating lots of tiny classes and it will be yet another
paradigm shift.

Is there a third option or a better way to accomplish the "limit scope" and
"maintain value between calls" functionality of my old static technique?

Any help/suggestions are greatly appreciated.

An old dog trying to learn new tricks,
John Kelsey
Jan 4 '06 #1
5 16403
John,

I too have missed local static variables. (1) is (class members) is the
best solution I've found. (2) seems like over-kill to me. I guess a third
option would be using VB.NET, but since it may be considered treason to
mention such a thing in a C# news group, pretend you didn't just read that
:)

--
Colin Neller
http://www.colinneller.com/blog
"John Kelsey" <ke*****@tacits .com> wrote in message
news:ez******** ******@TK2MSFTN GP11.phx.gbl...
Back in the "old" C/C++ days, I used to declare static variables inside
functions. Something like...

// just a silly example to demonstrate the technique
int foo(void)
{
static int NextVal = 0;
NextVal = (++NextVal) % 317;
return (NextVal);
}

I use this technique/style for many varied things but basically this gave
me a quick and easy to maintain a value between function calls while
limiting the visibility of the variable.

I'm struggling to find a C# equivalent technique. The best equivalents
I've discovered so far:

1) If foo is a member function of class fred, create a private variable in
fred on which foo operates. This is *OK* but gives the variable whole
class scope when only one function NEEDS it. It would also seem to
"clutter" the class namespace unnecessarily.

2) Create a small foo class with just a get method. NextVal would be a
private variable inside the small foo class. This is also *OK* but
setting up a separate class just to appropriately scope a variable and
maintain it between calls seems overkill. I understand writing the class
is not a huge deal, but I'll be creating lots of tiny classes and it will
be yet another paradigm shift.

Is there a third option or a better way to accomplish the "limit scope"
and "maintain value between calls" functionality of my old static
technique?

Any help/suggestions are greatly appreciated.

An old dog trying to learn new tricks,
John Kelsey

Jan 4 '06 #2
"John Kelsey" <ke*****@tacits .com> a écrit dans le message de news:
ez************* *@TK2MSFTNGP11. phx.gbl...

| Back in the "old" C/C++ days, I used to declare static variables inside
| functions. Something like...

| 1) If foo is a member function of class fred, create a private variable in
| fred on which foo operates. This is *OK* but gives the variable whole
class
| scope when only one function NEEDS it. It would also seem to "clutter"
the
| class namespace unnecessarily.

This is the "normal" way to do it; this way the variable has the same life
as the instance. It is also semantically correct because methods should not
have persistent state, to avoid threading problems; etc.

| 2) Create a small foo class with just a get method. NextVal would be a
| private variable inside the small foo class. This is also *OK* but
setting
| up a separate class just to appropriately scope a variable and maintain it
| between calls seems overkill. I understand writing the class is not a
huge
| deal, but I'll be creating lots of tiny classes and it will be yet another
| paradigm shift.

This will not make any difference because you will have to have a private
instance of the foo class in your class, just as with the straight variable,
this will be accessible to all methods of the class. Of course a static
class method could have even greater scope.

| Is there a third option or a better way to accomplish the "limit scope"
and
| "maintain value between calls" functionality of my old static technique?

Not AFAIK, see
http://blogs.msdn.com/csharpfaq/arch...11/130248.aspx

Using a private field really is the "normal" way :-)

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jan 4 '06 #3
Static local variables are also available in C++/CLI by the way.
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C# to C++ converter & VB to C++ converter
Instant J#: VB to J# converter

"John Kelsey" wrote:
Back in the "old" C/C++ days, I used to declare static variables inside
functions. Something like...

// just a silly example to demonstrate the technique
int foo(void)
{
static int NextVal = 0;
NextVal = (++NextVal) % 317;
return (NextVal);
}

I use this technique/style for many varied things but basically this gave me
a quick and easy to maintain a value between function calls while limiting
the visibility of the variable.

I'm struggling to find a C# equivalent technique. The best equivalents I've
discovered so far:

1) If foo is a member function of class fred, create a private variable in
fred on which foo operates. This is *OK* but gives the variable whole class
scope when only one function NEEDS it. It would also seem to "clutter" the
class namespace unnecessarily.

2) Create a small foo class with just a get method. NextVal would be a
private variable inside the small foo class. This is also *OK* but setting
up a separate class just to appropriately scope a variable and maintain it
between calls seems overkill. I understand writing the class is not a huge
deal, but I'll be creating lots of tiny classes and it will be yet another
paradigm shift.

Is there a third option or a better way to accomplish the "limit scope" and
"maintain value between calls" functionality of my old static technique?

Any help/suggestions are greatly appreciated.

An old dog trying to learn new tricks,
John Kelsey

Jan 4 '06 #4

"Joanna Carter [TeamB]" <jo****@not.for .spam> wrote in message
news:%2******** *******@TK2MSFT NGP10.phx.gbl.. .
"John Kelsey" <ke*****@tacits .com> a écrit dans le message de news:
ez************* *@TK2MSFTNGP11. phx.gbl...
--snip-- | 2) Create a small foo class with just a get method. NextVal would be a
| private variable inside the small foo class. This is also *OK* but
setting
| up a separate class just to appropriately scope a variable and maintain
it
| between calls seems overkill. I understand writing the class is not a
huge
| deal, but I'll be creating lots of tiny classes and it will be yet
another
| paradigm shift.

This will not make any difference because you will have to have a private
instance of the foo class in your class, just as with the straight
variable,
this will be accessible to all methods of the class. Of course a static
class method could have even greater scope.

foo, the function or the class can have public or private, appropriate for
what needs it. I just don't want anything accessing the variable NextVal in
the containing class fred except foo. The only way I understand to do that
in C# is to create a private variable inside a tiny class containing only a
public get method.

My first mentor insisted on appropriate data scoping. If foo is the only
thing that should see NextVal, it must be the only thing that can see
NextVal. In C#, so far this seems to require a mini-class.

Thanks for the help,
John Kelsey
Jan 4 '06 #5
"John Kelsey" <ke*****@tacits .com> a écrit dans le message de news:
u%************* ***@TK2MSFTNGP1 0.phx.gbl...

| foo, the function or the class can have public or private, appropriate for
| what needs it. I just don't want anything accessing the variable NextVal
in
| the containing class fred except foo. The only way I understand to do
that
| in C# is to create a private variable inside a tiny class containing only
a
| public get method.

All that means is that you then have to have an instance of that tiny class
in order to get at the public get method. Since you can't hide the class
declaration inside the method foo, where would you hold an instance of
TinyClass ?? And when you realise that you need a private field anyway, what
is the difference in visibilty between having aTiny.NextVal as a private
field or just nextVal ??

As I said before, you could declare a private static class with one static
property, thus avoiding the need for a local variable or field, but then
that would also be visible to, at least, all members of the containing
class.

| My first mentor insisted on appropriate data scoping. If foo is the only
| thing that should see NextVal, it must be the only thing that can see
| NextVal. In C#, so far this seems to require a mini-class.

I understand the requirement to scope appropriately, but the mini-class will
not enforce any- stricter scoping. C# simply does not allow any stricter
scoping than a private field in the class that contains the method.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jan 4 '06 #6

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

Similar topics

3
3937
by: Datta Patil | last post by:
Hi , #include<stdio.h> func(static int k) /* point2 : why this is not giving error */ { int i = 10 ; // static int j = &i ; /* point 1: this will give compile time error */ return k; } /* in above case where is variable k and j mapped in memory layout ? */
9
2830
by: AnandRaj | last post by:
Hi guys, I have a few doubts in C. 1. Why static declartions are not allowed inside structs? eg struct a { static int i; }; Throws an error ..
28
4647
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
12
2275
by: rodchar | last post by:
hey all, vb has a static keyword for variables, what is charp's equivalent,please? static tempVar as String thanks, rodchar
55
6249
by: Zytan | last post by:
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
3
2932
by: dmitrey | last post by:
Thank you in advance, Dmitrey
14
6027
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared static inside functions (i.e. local static objects) 5. objects declared at file scope.
10
2661
by: Pramod | last post by:
Hello to all of you, I want to know that what's the use to create static object. Thanks You Pramod Sahgal
11
8337
by: Jef Driesen | last post by:
I have the following problem in a C project (but that also needs to compile with a C++ compiler). I'm using a virtual function table, that looks like this in the header file: typedef struct device_t { const device_backend_t *backend; ... } device_t; typedef struct device_backend_t {
0
9518
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
10433
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...
1
10161
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
10000
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...
1
7538
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
6777
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();...
1
4112
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
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
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.