• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 253
  • Last Modified:

Static field in class, how does it work

Hello Experts :)

I am a C# newbie with some Delphi background.

I am struggling to understand the idea of static field in a class.


public class Jack
  public static int myField = 0;

then I can do something really strange to me...

I can assign value to a class, not even an instance of object of the class?

Jack.myField = 12;

1. How come can I use class like a variable which I do not even have to initialize?

2. How come can I change the value of ALL instances of object of the class Jacek by changing it somewhere in a code? It looks potentially very dangerous and far from a good practice of programming.

Any thoughts experts?

  • 2
1 Solution
1) That's the purpose of Static fields/ classes...to have the ability to call a function without having instantiate  the class...this is because that class is used throughout the app...meaning that every user uses it even though they are running their own app...
an example to illustrate this:  what if you wanted to know the count of all users on  your site...

if you instantiated a class, then it would always start at zero if you said something like this:
private int count = 0;

but if its static, the class is used by everyone...therefore the first person to log on would = 0,
but it would keep building for each additional user...

2)  answer 1 helps explain answer 2...you don't use this if you want all users variables to be user specific...but if you want to know about all users stats, you would use a static val
2)  answer 1 helps explain question 2...you don't use this if you want all users variables to be user specific...
but if you want something like in the example i gave (user's logged in counter), then you would use that....

yes, as stated, you don't instantiate static classes as you want all users/classes to see the last value it held and not to start at it's default as it would if it was instantiated...
HainKurtSr. System AnalystCommented:
in vb static is shared, may be a better wording ;)

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now