Friday, September 12, 2014

Static vs Instance Method & Static Variables

Instance Method

    class Program
    {
        static void Main()
        {
            Program p = new Program();
            p.ShowMessage();
        }

        public void ShowMessage()
        {
            Console.WriteLine("Message Showed");
            Console.ReadLine();
        }
}

Static Method

    class Program
    {
        static void Main()
        {
            Program.ShowMessage();
        }

        public static void ShowMessage()
        {
            Console.WriteLine("Message Showed");
            Console.ReadLine();
        }
    }


Different
  1. Instance method is for object instance. However Static Method is for class.
  2. Instance cannot call static method.
  3. Static Method take value is use Class Name, this is not work
  4. Static Method - Input given and return output (no state), regular class - input, store/maintain current state.
  5. Static Method - No Abstract, no inherit , no implementing as interface.

Static Variables
no matter how many objects of the class are created, there is only one copy of the static member.


class StaticVar
{
    public static int num;
    public void count()
    {
      num++;
    }
   public int getNum()
   {
      return num;
   }
}

static void Main(string[] args)
{
       StaticVar s1 = new StaticVar();
       StaticVar s2 = new StaticVar();
       s1.count();
       s2.count();
       Console.WriteLine("Variable num for s1: {0}", s1.getNum()); //Variable num for s1: 2
       Console.WriteLine("Variable num for s2: {0}", s2.getNum()); //Variable num for s2 :2
}




Static Function
Such functions can access only static variables. The static functions exist even before the object is created.

class StaticVarMethod
{
    public static int num;
   
    public void count()
    {
      num++;   //calling normal method, but static value change
    }
   public static int getNum()
   {
      return num;
   }
}

static void Main(string[] args)
{
    StaticVarMethod s = new StaticVarMethod();
    s.count();
    s.count();
    Console.WriteLine("Variable num: {0}", StaticVarMethod.getNum());  //Variable num: 2
}



No comments:

Post a Comment