Static members and Non-static members in C#

 

Static keyword is a modifier which can use to define types and member of types. So those members doesn't require object of a class for initialization and execution. A class is a collection of members where the members of a class are divided into two categories. Those are Static members and Non-static members/Instance members.

The members of a class who requires object of the class for initialization as well as execution are known as Non-static/Instance members. Whereas Static members doesn't require object of the class.

A variable that is declared using static modifier or a variable that is declared under static block are static variables and rest of the variables are instance variables.

            int empId = 100;

            static string companyName = "ABC";

As shown above we have one instance variable empId and one static variable companyName.

static void GetEmpInfo()

{

           int empId;

           string name;

}

As shown, we have static method GetEmpInfo() and all members within the method are static by default.

A static variable gets initialized immediately once the execution of class starts, whereas an instance variable gets initialized when the object of a class is created only and for each object new instance of a variable will create.

To access the static members we have to use the class name as shown below.

public class EmpInfo

{

           public static int id; ; //static members  

}

protected void Page_Load(object sender, EventArgs e)

{

           int id = EmpInfo.id 

}

To access the instance members we have to create the object of the class shown below.

public class EmpInfo

{

       public int id; //instance members

}

protected void Page_Load(object sender, EventArgs e)

{

      EmpInfo objEmp = new EmpInfo();

      int id = objEmp.id;           

}