In C# programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C#.
Let’s see the example of this keyword in C# that refers to the fields of current class.
using System; public class Employee { public int id; public String name; public float salary; public Employee(int id, String name,float salary) { this.id = id; this.name = name; this.salary = salary; } public void display() { Console.WriteLine(id + " " + name+" "+salary); } } class TestEmployee{ public static void Main(string[] args) { Employee e1 = new Employee(101, "Sonoo", 890000f); Employee e2 = new Employee(102, "Mahesh", 490000f); e1.display(); e2.display(); } }
In C#, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C#, static can be field, method, constructor, class, properties, operator and event.
Note: Indexers and destructors cannot be static.
A field which is declared as static, is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects.
It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc.
Let’s see the simple example of static field in C#.
using System; public class Account { public int accno; public String name; public static float rateOfInterest=8.8f; public Account(int accno, String name) { this.accno = accno; this.name = name; } public void display() { Console.WriteLine(accno + " " + name + " " + rateOfInterest); } } class TestAccount{ public static void Main(string[] args) { Account a1 = new Account(101, "Sonoo"); Account a2 = new Account(102, "Mahesh"); a1.display(); a2.display(); } }
Output
101 Sonoo 8.8 102 Mahesh 8.8
The C# static class is like the normal class but it cannot be instantiated. It can have only static members. The advantage of static class is that it provides you guarantee that instance of static class cannot be created.
Question
In C#, we cannot create an object of the __ class.