Static
constructors are used to initialize static fields of a class. Static
constructor is called only once. It is called prior to initializing any object,
any static members are referenced.
using System; class Circle { static float PI; int radius; static Circle() { Console.WriteLine("Static constructor is called"); PI = 3.14f; } public Circle(int radius) { Console.WriteLine("Instance constructor is called with radius {0}", radius); this.radius = radius; } public float getArea() { return PI * radius * radius; } } class Program { static void Main(string[] args) { Circle circle1 = new Circle(5); Circle circle2 = new Circle(6); float area1 = circle1.getArea(); float area2 = circle2.getArea(); Console.WriteLine("area1 : {0}", area1); Console.WriteLine("area2 : {0}", area2); } }
Output
Static constructor is called Instance constructor is called with radius 5 Instance constructor is called with radius 6 area1 : 78.5 area2 : 113.04
No comments:
Post a Comment