C# static Keyword
In C#, if we use a static
keyword with class members, then there will be a single copy of the type member.
And all objects of the class share a single copy instead of creating individual copies.
C# Static Variables
If a variable is declared static
, we can access the variable using the class name. For example,
In the above example, we have created a static variable named department
. Since the variable is static, we have used the class name Student
to access the variable.
Example: C# Static Variable Vs. Instance Variable
In the above program, the Student class has a non-static variable named studentName
and a static variable named schoolName
.
Inside the Program
class,
s1.studentName
/s2.studentName
- calls the non-static variable using objectss1
ands2
respectivelyStudent.schoolName
- calls the static variable by using the class name Since theschoolName
is the same for all students, it is good to make theschoolName
static. It saves memory and makes the program more efficient.
C# Static Methods
Just like static variables, we can call the static methods using the class name.
Here, we have accessed the static method directly from Program
classes using the class name.
When we declare a method static, all objects of the class share the same static method.
Note: In C#, the Main method is static. So, we can call it without creating the object!
Static methods and instance variable
Static methods cannot make use of instance members (non-static). If you think about it, it is very natural for this restriction. Instance members belong to a specific object, where as static methods are defined on the whole class, without any intention to manipulate variable of any specific object.
Static methods cannot make use of instance members, whereas normal methods (non-static methods) can access any type of members (static or non-static)!
Last updated