Wednesday, 10 April 2013

Static Class and Methods in C#

Static Class and Methods in C#

A static class is never instantiated. The static keyword on a class enforces that a type not be created with a constructor. In the static class, we access members directly on the type. A static class cannot have non-static members. All methods, fields and properties in it must also be static.

Example

To start, there are two classes in this program: the Program class, which is not static, and the ABC class, which is static. You cannot create a new instance of ABC using a constructor. Trying to do so results in an error.

Inside the ABC class, we use the static modifier on all fields and methods. Instance members cannot be contained in a static class.

using System;
class Program
{
    static void Main()
    {
      // Cannot declare a variable of type ABC.
      // This won't blend.
      // ABC abc= new ABC ();
      // Program is a regular class so you can create it.
      Program program = new Program();
      // You can call static methods inside a static class.
      ABC._ok = true;
      ABC.Blend();
    }
}

static class ABC
{
    // Cannot declare instance members in a static class!
    // int _test;
    // This is ok.
    public static bool _ok;
    // Can only have static methods in static classes.
    public static void Blend()
    {
      Console.WriteLine("Blended");
    }
}

Output
Blended

No comments:

Post a Comment