C# Static Classes

Description

A class can be marked static, indicating that it must be composed solely of static members and cannot be subclassed. The System.Console and System.Math classes are good examples of static classes.

Note

Classes (but not structs) can be declared as static. A static class can contain only static members and cannot be instantiated with the new keyword.

One copy of the class is loaded into memory when the program loads, and its members are accessed through the class name.

Both classes and structs can contain static members.

A static class can contain only static members. We cannot instantiate the class using a constructor. We must refer to the members through the class name.

Example

The following code defines a static class to store message.


using System;//from ww w  .j a v  a 2s  .  c  o m

public static class MyStaticClass
{

    public static string getMessage()
    {
        return "This is a static member";
    }

    public static string StaticProperty
    {
        get;
        set;
    }

}

public class MainClass
{
    static void Main(string[] args)
    {
        Console.WriteLine(MyStaticClass.getMessage());
        MyStaticClass.StaticProperty = "this is the property value";
        Console.WriteLine(MyStaticClass.StaticProperty);

    }
}

The output:

Example 2

The following code shows how to use static class to create utility class. The utility class is for math calculation.


using System;  // w  ww.j  a va2  s  .  c o m
  
static class MathFunction {  
  // 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 MainClass {  
  public static void Main() {    
    Console.WriteLine("Reciprocal of 5 is " + 
                      MathFunction.reciprocal(5.0)); 
 
    Console.WriteLine("Fractional part of 4.234 is " + 
                      MathFunction.fracPart(4.234)); 
 
    if(MathFunction.isEven(10)) 
      Console.WriteLine("10 is even."); 
 
    if(MathFunction.isOdd(5)) 
      Console.WriteLine("5 is odd."); 
 
    // The following attempt to create an instance of  
    // MathFunction will cause an error. 
//  MathFunction ob = new MathFunction(); // Wrong! 
  }  
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor