C#.NET : Static Class


  1. A static class can be created using a keyword called ―static‖ used at the class definition.
  2. A static class can contain only static members (static data members and static methods).
  3. You can‘t create an object for the static class.
  4. Advantages :

    • If you declare any non-static member, it generates a compile time error; so that it is guaranteed that the class contains only static members; no chance of declaring non-static member accidentally.
    • When you try to create an instance to the static class, it again generates a compile time error, because the static members can be accessed directly with its class name.

Syntax :

 static class classname
  {
   //static data members
   //static methods
  }

Program for Static Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticClassesDemo
{
  static class Sample
   {
    public static string SampleStaticMember = "This is my static data member";
    public static void SampleStaticMethod()
     {
       Console.WriteLine("This is my static method.");
     }
   }

  class Program
   {
    static void Main(string[] args)
    {
     Console.WriteLine(Sample.SampleStaticMember);
     Sample.SampleStaticMethod();
     Console.Read();
    }
   }
}
0 Komentar untuk "C#.NET : Static Class"

Back To Top