Tuesday, August 14, 2007

CSharp Tip #1 : Static Classes

In .NET Framework 1.x, Static Classes are created by defining a class with a private constructor with one or more static members so that instance of the class cannot be created using new operator.

In .NET Framework 2.0 the need for such a private constructor is avoided by using a static keyword along with the class definition. Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values.

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

namespace VikasGoyal.StaticClasses
{
  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine(StaticClass.getName());
          Console.WriteLine(StaticClass.getName());
          Console.WriteLine(StaticClass.getName());
      }
  }
  static class StaticClass
  {
      private static string name;
      static StaticClass()
      {
          name = "Vikas Goyal";
          Console.WriteLine("In Constructor");
      }
      public static string getName()
      {
          return name;
      }
  }
}
OUTPUT
In Constructor
Vikas Goyal
Vikas Goyal
Vikas Goyal

No comments:

Post a Comment