C# static field
In C#, static filed is the one which belongs to the class not instance hence we don’t need to create instance to access static field. The memory is assigned only once to a static field at the time of class loading which is common among all the objects.
Advantages:
- We don't need to create object to access static data that's why it is memory efficient.
- The data which is common among all the objects is made static to avoid redundancy of data.
C# Static Filed Example:
Let's see a simple example of static field in C#.
using System;
public class Student
{
int id;
string course,name;
static int batch=2017;
public Student(int id,string name,string course)
{
this.id=id;
this.name=name;
this.course=course;
}
public void show()
{
Console.WriteLine(id+" "+name+" "+course+" "+batch);
}
public static void Main(string[] args)
{
Student s1=new Student(101,"Ravi Dubey","M.C.A.");
Student s2=new Student(102,"Ravi Malik","B. Tech.");
s1.show();
s2.show();
}
}
Output
101 Ravi Dubey M.C.A. 2017 102 Ravi Malik B. Tech. 2017C# Static field Example: Counting Number of instances
using System;
public class Student
{
int id;
string course,name;
static int batch=2017;
static int count=0;
public Student(int id,string name,string course)
{
this.id=id;
this.name=name;
this.course=course;
count++;
}
public void show()
{
Console.WriteLine(id+" "+name+" "+course+" "+batch);
}
public static void Main(string[] args)
{
Student s1=new Student(101,"Ravi Dubey","M.C.A.");
Student s2=new Student(102,"Ravi Malik","B. Tech.");
Student s3=new Student(103,"Ravi Gautam","B.C.A.");
s1.show();
s2.show();
s3.show();
Console.WriteLine("Number of students are : "+count);
}
}
Output
101 Ravi Dubey M.C.A. 2017 102 Ravi Malik B. Tech. 2017 103 Ravi Gautam B.C.A. 2017 Number of students are : 3