Click here to Skip to main content
15,745,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using static variable in a program is a "not". But I don't understand the problem that would arise, in a program, if I use static variable or static function....

What I have tried:

DOnt know just need help from you
Updated 22-Dec-22 3:53am
Richard MacCutchan 22-Dec-22 9:52am    
It all depends on how you use them and what they do. There is no hard and fast rule, but it it is rare for them to be required.
PIEBALDconsult 22-Dec-22 10:08am    
You may be thinking of a "global" variable. Static members of classes are OK. Unless you do something stupid with it.

1 solution

Using static variable in a program is a "not".
Either the person who told you that doesn't know what they're talking about, or you missed a lot of context in what was said.

static fields/properties/methods have plenty of valid uses in writing code. You just need to understand what you're doing with them.

For example, a static field can usually* only store a single value for the entire lifetime of the process. If you're writing a web application, for example, then using static fields to store user-specific data is a serious error, because the data will be overwritten with data for other users.

But a blanket ban on static members based on one example of incorrect behaviour resulting from not understanding them is a serious overreaction.

* "Usually", because you can have "thread-static" fields which store a different value for each thread:
ThreadStaticAttribute Class (System) | Microsoft Learn[^]

Or you can use something like the ThreadLocal<T> class, where a single static instance of the class stores a different value for each thread:
ThreadLocal<T> Class (System.Threading) | Microsoft Learn[^]

Or you can have static properties which return a different value for each logical "call context" - for example, the HttpContext.Current property.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900