October 3, 2017
static constructors
Static constructor is used to initialize static variables defined in a class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication6 { class Program { static int num; int a = 10; static Program() { num = 10; // a = 40; this is error } public Program() { } public Program( int num ) { Console.WriteLine(num); } static void Main(string[] args) { Program p1,p2,p3; p1 = new Program(10); p2 = new Program(10); p3 = new Program(10); Program obj = new Program(); } } } //////////////// // Static constructor - Another example using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace ConsoleApplication6 { class Program { public static readonly Color BackColor; static Program() { DateTime now = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) { BackColor = Color.Green; } else { BackColor = Color.Red; } } static void Main(string[] args) { Console.WriteLine(@"User-preferences: BackColor is: " + Program.BackColor.ToString()); } } }