Difference between static members and instance members
Introduction
Instance members are unique to each object of the class, whereas static members are the same for all objects of a class. Let's say we have a class named 'Student.' Each student will have a different name, ID, and address. However, the name of the school is going to be the same for all students. So the name of the school can be declared as a static member, whereas the other attributes of the student can be declared as instance members.
Example:
This is an example of a class named Student
class Student
{
public string Name;
public int ID;
public string Address
}
Let's now create 2 objects of this class Student. The instance variables of the students have its own unique values as you can see below.
Student Vipin = new Student();
Vipin.Name = "Vipin";
Vipin.ID = 20409068;
Vipin.Address = "Bangalore";
Student Neethu = new Student();
Neethu.Name = "Neethu";
Neethu.ID = 1234;
Neethu.Address = "Chennai";
Now, let's consider something that is actually the same for all students; let's say the name of the school is going to be the same for all students.
class Student
{
public string Name;
public int ID;
public string Address
public static string SchoolName = "XYZ School";
}
We can access 'SchooName' without creating 'Student' instances. Please see below.
string schoolName = Student.SchoolName;
Comments
Post a Comment