In this blog, I will discuss static classes and static class members in C#,
Static Classes and Static Class Members
A static class is a class which can not be instantiated. We do not need to create an object of a static class like we did in non-static classes. Members of static classes can be accessed directly using the class name followed by a (.) and class member name. Class Members can be methods, fields, properties, or events. A static class can contain only the static members while a non-static class can contain static members. Also, Static classes are by-default sealed so they cannot be inherited.
To declare a class and its members as static, 'static' keyword are used as shown below,
- using System;
-
- namespace Tutpoint
- {
-
- static class TutLovers
- {
-
- public static int val_Static;
-
-
- public static void Addition_Static()
- {
- Console.Write("Static Method");
- }
-
-
- public static int Addition_NonStatic
- {
- get; set;
- }
- }
For more understanding see the example shown below,
The example shown below contains two non-static classes named "TutLovers" and "TutHaters". Here a class "TutLovers" contains static as well as non-static methods and variable. When we access them from class "TutHaters" then, For the static members, they will be accessed directly using class name followed by (.) and
For non-static members, we have created an object of that class.
- using System;
-
- namespace Tutpoint
- {
- class TutLovers
- {
- public static int val_Static;
-
- public int val_NonStatic;
-
- public static void Addition_Static()
- {
- Console.Write("Static Method");
- }
-
- public void Addition_NonStatic()
- {
- Console.Write("Non-Static Method");
- }
- }
-
-
- class TutHaters
- {
- public void Haters()
- {
-
- TutLovers tutLovers = new TutLovers();
-
-
- tutLovers.Addition_NonStatic();
- tutLovers.val_NonStatic = 5;
-
-
- TutLovers.Addition_Static();
- TutLovers.val_Static = 5;
-
-
-
- tutLovers.Addition_Static();
-
-
- */
- TutLovers.Addition_NonStatic();
- }
- }
-
- }
As shown above, when we try to access static member with an instance reference, it will create an error as "Members 'TutLovers.Addition_Static()' can not be accessed with an instance reference; qualify it with a type name instead" and when we try to access non-static member using class_name then it will create an error as "An object reference is required for the non-static field, method or property 'TutLovers.Addition_NonStatic()'".
Note
- There exists only one copy for every static member regardless of the number of instances of the class.
- Static methods can access only static members. They cannot access non-static members.
- A static class can only contain static members.