CodeBlanks Logo Icon CodeBlanks

Static classes

C# course · Intermediate · Lesson 32/116

Learn how to define and use static classes.

Static classes

A static class cannot be instantiated and may contain only static members. It is declared as static class Config { ... }.

Static classes are ideal for collecting helper and utility functions: Math, Convert, Console are examples. Because no instance can be created, new Config() is a compile error. Members must also be marked static.

When to use a static class?

If every member of a class is already static, marking the class itself static is recommended. It prevents accidental instantiation and signals intent.

For example, a StringHelper class that only has static methods like Capitalize and Truncate is a good candidate. If you need to hold instance state, a static class is wrong; use a normal class.

Exercise Configuration class

Define a static class Config. Add a public static string AppName = "Quiz"; field. In Main, print Config.AppName.

Show example solution
Add `static class Config { public static string AppName = "Quiz"; }`. In Main write `Console.WriteLine(Config.AppName);`.
Example solution:
using System;

static class Config
{
    public static string AppName = "Quiz";
}

class Program
{
    static void Main()
    {
        Console.WriteLine(Config.AppName);
    }
}

Test yourself

  1. Match: static class properties

    static class
    cannot be instantiated
    new Config()
    compile error
    member
    must be static
    use case
    helper functions
  2. Fill in the blank: static class declaration

    static ____
    {
        public static string AppName = "Quiz";
    }
    Show answer
    static class Config
    {
        public static string AppName = "Quiz";
    }
  3. Which statement about static classes is FALSE?

    • A static class cannot be instantiated.
    • All members of a static class must be static.
    • Math is a static class.
    • A static class can have an instance constructor.
    Show answer

    A static class can have an instance constructor. — Correct (false statement). A static class cannot have an instance constructor; only a static constructor is allowed.

All lessons in Intermediate