Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0145 Static Class

Classes (but not structs) can be declared as static. A static class can contain only static members and cannot be instantiated with the new keyword. One copy of the class is loaded into memory when the program loads, and its members are accessed through the class name. Both classes and structs can contain static members. A static class can contain only static members. We cannot instantiate the class using a constructor. We must refer to the members through the class name. using System; public static class MyStaticClass { public static string getMessage() { return "This is a static member"; } public static string StaticProperty { get; set; } } public class MainClass { static void Main(string[] args) { Console.WriteLine(MyStaticClass.getMessage()); MyStaticClass.StaticProperty = "this is the property value"; Console.WriteLine(MyStaticClass.StaticProperty); } } The output: This is a static member this is the property value