Monday, April 21, 2014

Static Methods

Static methods, can only be accessed by Class because those are not instance level methods.Refer to the highlighted text in the code below. In order to access static methods the syntax is <ClassName>.<methodName>

When to use? Static methods are good for utility methods that do not depend on a particular instance.

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 static 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);
            Car.setNbrOfWheels(6);
            Console.WriteLine("CAR 2 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car2.color, car2.typeOfCar, Car.nbrOfWheels);
            Car.setNbrOfWheels(8);
            Console.WriteLine("CAR 1 : COLOR = {0} / CAR TYPE = {1} / WHEELS = {2}", car1.color, car1.typeOfCar, Car.nbrOfWheels);
            Console.ReadLine();            
        }
    }
}

Restrictions: 
  • Static methods cannot access non-static variables. If at all this is done, it will lead to compile time error.
  • "this" operator cannot be used in static methods. 
  • In order to set non-static variables, an instance needs to be created within the static methods. However, this would not make any sense as the object scope would be only in the static method.
The Why Section : If one really needs to understand any topic its very important to understand the whys? I do not like taking things on face value. Its good to know the facts, but its very important to understand the reasoning behind each fact. Lets go through the below questions to re-inforce the concepts.


1. Why cannot static methods access non-static variables (except by creating an instance within static method)?
A static method is associated with the class, so it cannot access any non-static variables. It would not know which instance's non-static variables to use.


2. Why this operator cannot be used in static method?
"this" implies an object/instance that is the reason this operator cannot be used in static method.



No comments:

Post a Comment