Monday, April 21, 2014

Static Data/Field

The concept is very simple that I have tried to explain with the screen-shot below.

Assumption : All cars whatsoever, will have same number of wheels.

                           In-memory allocation would like as below



  • In above picture - nbrOfWheels is defined static so that is being shared by all the objects/instances of the Class "Car". That means if nbrOfWheels is changed, all objects will see the change.
  • All Car instances (Car1, Car2), get their own copies of non-static fields. Meaning, Car1 will have its own color and carType and Car2 will have its own color and carType.

How this works internally?
     As the picture depicts, the CLR allocates the memory to the object only once. After that all the objects refer to the same memory location.

Lets look at the code below...

using System;

namespace StaticDataExample
{

    class Car
    {
        public static int nbrOfWheels = 4;
        public string color, typeOfCar;

        public Car(string color, string typeOfCar)
        {
            this.color = color;
            this.typeOfCar = typeOfCar;
        }

        public void setNbrOfWheels (int wheels)
        {
            nbrOfWheels = wheels;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car("Red", "SUV-AWD");
            Car car2 = new Car("Red", "CAR");

            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            car1.setNbrOfWheels(6);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            car2.setNbrOfWheels(8);
            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.ReadLine();            
        }
    }
}
output
  • The code above, shows how the static field is shared by all the instances.
  • Once the static field is changed by one object, the shared copy is changed too.
  • Static field is accessed by <Classname>.<staticVariableName>, in above example, refer to the highlighted portion of the code. Instance cannot at all access the static fields.

No comments:

Post a Comment