C# Static Classes
In this chapter you will learn:
- What are Static Classes
- Note for static class
- Example for C# Static Classes
- How to use static class to create utility class
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;// ww w .j a va2 s .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; //from ww w .j av a 2s . c om
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.
Next chapter...
What you will learn in the next chapter: