Static in C# - Erklärung und Verwendung

In C# bedeutet static, dass ein Element nicht zu einer konkreten Objekt-Instanz gehört, sondern zur Klasse selbst. Es existiert also genau einmal im gesamten Programm.

Normalerweise gilt:

var p1 = new Person();
var p2 = new Person();

p1 und p2 haben jeweils ihre eigenen Felder.

Mit static gilt: → Es gibt nur eine einzige Version für alle.


1. Statische Felder (static fields)

Ein statisches Feld speichert Daten, die von allen Objekten einer Klasse gemeinsam genutzt werden.

class Person
{
    public static int AnzahlPersonen = 0;
 
    public Person()
    {
        AnzahlPersonen++;
    }
}

Verwendung:

Person p1 = new Person();
Person p2 = new Person();
 
Console.WriteLine(Person.AnzahlPersonen); // 2

Wichtig: - Zugriff über den Klassennamen:

Person.AnzahlPersonen

Sinnvolle Einsatzfälle: - Zähler - Globale Konfiguration - Gemeinsamer Zustand


2. Statische Properties

class GameSettings
{
    private static int maxPlayers = 4;
 
    public static int MaxPlayers
    {
        get { return maxPlayers; }
        set
        {
            if (value > 0)
                maxPlayers = value;
        }
    }
}

Verwendung:

GameSettings.MaxPlayers = 8;
Console.WriteLine(GameSettings.MaxPlayers);

3. Statische Methoden

class MathHelper
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

Verwendung:

int result = MathHelper.Add(3, 5);

Bekannte Beispiele:

Console.WriteLine("Hallo");
Math.Sqrt(16);
DateTime.Now;

4. Kombination: static Feld + static Methode

class Logger
{
    private static int logCount = 0;
 
    public static void Log(string message)
    {
        logCount++;
        Console.WriteLine($"[{logCount}] {message}");
    }
}

5. Static Classes

static class StringUtils
{
    public static bool IsNullOrEmpty(string text)
    {
        return text == null || text.Length == 0;
    }
 
    public static string Reverse(string text)
    {
        return new string(text.Reverse().ToArray());
    }
}

6. Typische sinnvolle Einsatzgebiete

Zentrale Konfiguration

static class AppConfig
{
    public static string DatabaseConnectionString = "...";
    public static bool DebugMode = true;
}

Hilfsklassen

static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(double c)
        => c * 9 / 5 + 32;
}

Spielzustand

static class GameState
{
    public static int Score = 0;
    public static int Lives = 3;
}

Zähler

class User
{
    public static int UserCount = 0;
 
    public User()
    {
        UserCount++;
    }
}

7. Wichtige Regeln

  1. Static kann nicht auf Instanzdaten zugreifen:
class Test
{
    int x;
 
    static void Foo()
    {
        // x = 5; ❌
    }
}
  1. Instanzmethoden dürfen auf static zugreifen:
void Bar()
{
    Console.WriteLine(GameState.Score);
}

Faustregel: > Wenn etwas logisch zur Klasse gehört und nicht zu einem einzelnen Objekt, dann ist static sinnvoll.