Main Difference between them are
- A variable declared using static modifier or Declared under a static block were know as static variables. Rest of all were instance variables.
- A static variable gets initialize once the execution of class starts. Where as instance variable gets initialize only after creating object of class.
- The Minimum and Maximum number of times an static variable gets initialize will be one and only once. Where as in case Instance it will be Zero or N.
- As Static variables were only a single copy for the complete class modifications made by one object will be reflected to other. Where as Instance variables were separated copy's for each object changes of one will not reflect to the other.
While referring to instance members we require to refer them by using the object of class. Where as we refer to static members by using class name.
Sample Example of Static variable and Instance variable :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class staticvariables
{
int x = 100; // instance
static int y = 200; //static
static void Main(string[] args)
{
int z = 300; // static
staticvariables obj = new staticvariables();
Console.WriteLine(staticvariables.y);
Console.WriteLine(obj.x);
Console.WriteLine(z);
Console.ReadLine();
}
}
}
OUTPUT :
200
100
300
200
100
300
No comments:
Post a Comment