Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Generally static varibles are intalized whenever the class excuted but why should share

the static varibles to the instances of the class

What I have tried:

Generally static varibles are intalized whenever the class excuted but why should share

the static varibles to the instances of the class
Posted
Updated 25-Feb-17 1:56am
v2
Comments
[no name] 25-Feb-17 6:16am    
And what did the massive research that you must have done tell you when you researched whatever your actual question is, reveal to you?
Graeme_Grant 25-Feb-17 6:19am    
Why is there air? It is what it is. Static variable in a class is shared.

Because that is what they are there for.
Static variables are ones which are common to all instances, or that don't require an instance of the class in order to be used.

Think of cars for a moment:
How many wheels has a car?

That's simple - all cars have four wheels: if they had one, they would fall over, two and they would be motorcycles, three would make them a tricycle, and five or more means they belong in Hollywood, rather than on the road. You don't need to ask the question about a specific car, because all cars share the same information.
What color is a car?

That's harder, because "my car" is red, "your car" is blue, "this car" is green, and so on - the color of the car depends on exactly which car you are referring to.

In C# terms, the NumberOfWheels property is static - shared by all instances and accessed via the class name:
C#
Console.Writeline(Car.NumberOfWheels);
While the Color property is non static (instance based) and requires a specific instance of the class to use:
C#
Car myCar = new Car(...);
Car yourCar = new Car(...);
...
Console.WriteLine("My car is {0}, your car is {1}", myCar.Color, yourCar.Color);

Make sense?
 
Share this answer
 
v2
Quote:
Why

Because the language is designed that way !
these variables are static because they are different from ordinary variable in classes.
They exist because the designers have encountered their need.
If you don't need them, just don't use them.

Why Spring succeed to Winter ?
 
Share this answer
 
v2

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