A static class cannot be derived from a non-static as well as static class. Static classes are by default sealed so you cannot inherit them. It can only inherit the Object class.
Code Snippet
- public class NormalClassA
- {
- }
- public static class StaticClassC : NormalClassA
- {
- }
- public static class StaticClassD : StaticClassC
- {
- }
Below is error description.
You cannot declare an instance field inside static class(outside non-static method and constructor).But you can use an instance variable inside static constructor and static method.
You can declare a read-only static variable in static class but it can only be changed in a non-static constructor. But you cannot change the read-only static variable from inside a static method.
You can declare and initialize a constant variable inside static class once and thereafter it can't be changed.
You cannot have non-static constructor inside a static class. Since we can't create an object of the static class to invoke it.
You can declare a static variable at first inside the static class which can be later initialized/changed from inside a constructor and/or from a static method.
Below is code snippet.
- public static class StaticClassD
- {
-
-
-
-
- readonly static int k;
- static int n;
- const int i = 90;
-
-
-
-
- static StaticClassD() { k++; n++; int data = 9; }
-
-
-
- public static void ChangedTextStaticMethod()
- {
- int d = 88;
-
- n++;
- Console.WriteLine("Value of static readonly variable k is :"+ k);
- Console.WriteLine("Value of static variable n is :" + n);
- Console.WriteLine("Value of constat variable i is :" + i);
- Console.WriteLine("Value of instance variable d is :" + d);
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- StaticClassD.ChangedTextStaticMethod();
- }
- }
Below is output.
Static default constructor execution order is from bottom to top (child to parent). And, Non-Static default constructor execution order is from top to bottom (parent to child).
Below is the code snippet.
- class NormalClassB
- {
- static NormalClassB()
- {
- Console.WriteLine("Static constructor of NormalClassB Called");
- }
- public NormalClassB()
- {
- Console.WriteLine("Non-Static constructor of NormalClassB Called");
- }
- }
-
- class NormalClassC :NormalClassB
- {
- static NormalClassC()
- {
- Console.WriteLine("Static constructor of NormalClassC Called");
- }
- public NormalClassC()
- {
- Console.WriteLine("Non-Static constructor of NormalClassC Called");
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
-
-
- NormalClassC normalClassC = new NormalClassC();
- }
- }
Below is output screen.