New Features in C# 2.0—Static Classes: How do I do that?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

How do I do that?

To create a static class, just add the static keyword before the class name and make sure your static class meets the criteria described earlier for static members. Also, note that static classes have the following restrictions:

  • They can contain only static members.
  • It is not legal to instantiate a static class.
  • All static classes are sealed (you cannot derive them from a static
class).

In addition to these restrictions, a static class cannot contain a constructor. Example 1-6 shows the proper use of a static class.

Example 1-6. Using static classes

#region Using directives
using System;
#endregion
 
namespace StaticClass
{
  public static class CupConversions
  {
    public static int CupToOz(int cups)
    {
      return cups * 8; // 8 ounces in a cup
    }
 
    public static double CupToPint(double cups)
    {
      return cups * 0.5; // 1 cup = 1/2 pint
    }
 
    public static double CupToMil(double cups)
    {
      return cups * 237; // 237 mil to 1 cup
    }
 
    public static double CupToPeck(double cups)
    {
      return cups / 32; // 8 quarts = 1 peck
    }
 
    public static double CupToBushel(double cups)
    {
      return cups / 128; // 4 pecks = 1 bushel
    }
  }
 
  class Program
  {
    static void Main(string[ ] args)
    {
      Console.WriteLine("You might like to know that " +
        "1 cup liquid measure is equal to: ");
      Console.WriteLine(CupConversions.CupToOz(1) + " ounces");
      Console.WriteLine(CupConversions.CupToPint(1) + " pints");
      Console.WriteLine(CupConversions.CupToMil(1) + " milliliters");
      Console.WriteLine(CupConversions.CupToPeck(1) + " pecks");
      Console.WriteLine(CupConversions.CupToBushel(1) + " bushels");
    }
  }
}

Output:

You might like to know that 1 cup liquid measure is equal to:
8 ounces
0.5 pints
237 milliliters
0.03125 pecks
0.0078125 bushels

The Program class’s main method makes calls on the static methods of the CupConversions class. Because CupConversions exists only to provide several helper methods, and no instance of CupConversions is ever needed, it is safe and clean to make CupConversions a static class.


Previous_Page_.gif Next_Page_.gif


Personal tools