Static Classes


C# 2.0 added the ability to create static classes. There are two key features of a static class. First, no object of a static class can be created. Second, a static class must contain only static members. The main benefit of declaring a class static is that it enables the compiler to prevent any instances of that class from being created. Thus, the addition of static classes does not add any new functionality to C#. It does, however, help prevent errors.

A static class is created by modifying a class declaration with the keyword static, as shown here:

 static class class-name { // ...

Within the class, all members must be explicitly specified as static. Making a class static does not automatically make its members static.

The main use of a static class is to contain a collection of related static methods. Here is an example. The static class NumericFn contains a group of static methods that operate on a numeric value. Because all of the members of NumericFn are declared static, the class can also be declared static, which prevents it from being instantiated.

 // Demonstrate a static class. using System; static class NumericFn {   // Return the reciprocal of a value.   static public double reciprocal(double num) {     return 1/num;   }   // Return the fractional part of a value.   static public double fracPart(double num) {     return num - (int) num;   }   // Return true if num is even.   static public bool isEven(double num) {     return (num % 2) == 0 ? true : false;   }   // Return true of num is odd.   static public bool isOdd(double num) {     return !isEven(num);   } } class StaticClassDemo {   public static void Main() {     Console.WriteLine("Reciprocal of 5 is " +                       NumericFn.reciprocal(5.0));     Console.WriteLine("Fractional part of 4.234 is " +                       NumericFn.fracPart(4.234));     if(NumericFn.isEven(10))       Console.WriteLine("10 is even.");     if(NumericFn.isOdd(5))       Console.WriteLine("5 is odd.");     // The following attempt to create an instance of     // NumericFn will cause an error. //  NumericFn ob = new NumericFn(); // Wrong!   } }

The output from the program is shown here:

 Reciprocal of 5 is 0.2 Fractional part of 4.234 is 0.234 10 is even. 5 is odd.

Notice that the last line in the program is commented-out. Because NumericFn is a static class, any attempt to create an object will result in a compile-time error. It would also be an error to attempt to give NumericFn a non-static member.

One last point: Although a static class cannot have an instance constructor, it can have a static constructor.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net