When a Class has Static Keyword then it act as a Static Class.
Static Class and its members do not need any Object to call them, you can use the
class name directly to call any members.
The Static class and its members enable you to access the data and member functions of the class without creating an instance of the Class (Object of the Class).
When we create any member to Static that means it share the same memory location.
Static members do not need to be instantiated. you can use a Static Class if data or methods declared in the class do not depend on the behaviour of an Object.
When the Class has Static keyword then that class is act as a Static Class as shown in below code , I have created a Student class with Static Keyword and inside this Student Class StudentId and StudentName are two static properties and one Static parameterless constructor and also has one Static method with name PrintName().
public static class Student
{
public static int StudentId;
public static string StudentName=string.Empty;
static Student()
{
StudentId = 1;
StudentName = "James Berry";
}
public static void PrintName()
{
Console.WriteLine("Your Name is :-",
StudentName);
}
}
Note :- We can not declare instance members in static class , it only have static members as shown in below image , I have declared StudentId as a instance member and it is throwing compile time error.
Note :- We can not declare instance Constructor in static class , it only have static Constructors as shown in below image , I have declared one instance constructor and it is throwing compile time error.
Note :- We can not declare parameterized Static Constructor in static class , it only have parameterless static Constructors as shown in below image , I have declared one parameterized Static constructor and it is throwing compile time error.
Note :- We Can not create Object/Instance of Static Class with New Keywords. as shown in below image , I have created one instance of Static Class Student and it is throwing compile time error.
Note :- We can access members of Static Class using the ClassName as shown in below image, Employee is the Static Class and EmployeeId is the member of Static Class Employee.
Points to Remember :-
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.