Monday, December 6, 2010

Understanding the Static constructors in c sharp:

Static constructors are used to initialize the static variables of a class. These variables are created using the static keyword and they store values that can be shared by all the instances of class. These constructors have an implicit private access. The constructors will be invoked only once during the execution of a program.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calc
{
class Calculator
{
private static int number1, number2, total;
static Calculator()
{
number1 = 10;
number2 = 20;
}
public void AddNumber()
{
total = number1 + number2;
}
public void DisplayNumber()
{
Console.WriteLine("The Total is:{0}", total);
}
public static void Main (string[] args)
{
Calculator c1 = new Calculator();

c1.AddNumber();
c1.DisplayNumber();
Console.ReadLine();
}

}
}

1 comment:

Tony said...

Nice post

Recent Posts