C# Language Static Classes Static Classes

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The "static" keyword when referring to a class has three effects:

  1. You cannot create an instance of a static class (this even removes the default constructor)
  2. All properties and methods in the class must be static as well.
  3. A static class is a sealed class, meaning it cannot be inherited.

public static class Foo
{
    //Notice there is no constructor as this cannot be an instance
    public static int Counter { get; set; }
    public static int GetCount()
    {
        return Counter;
    }
}

public class Program 
{
    static void Main(string[] args)
    {
        Foo.Counter++;
        Console.WriteLine(Foo.GetCount()); //this will print 1
        
        //var foo1 = new Foo(); 
        //this line would break the code as the Foo class does not have a constructor
    }
}


Got any C# Language Question?