Class (C#)

A class in C# is a blueprint for creating objects, defined with the class keyword.

This page covers Class in C#. For a language-agnostic introduction, see Class.

Defining a Class#

public class Player
{
}

public is the access modifier — it means the class can be used from anywhere in the program. The class body sits between the curly braces.

By convention, class names use PascalCase: Player, OddsAndEvens, RockPaperScissors.

Adding Fields and Properties#

A field stores data on the object. A property provides controlled access to that data.

public class Player
{
    public string Name;
    public int WinCount { get; set; }
}

Adding a Method#

A method defines what the object can do.

public class Player
{
    public string Name;

    public void Greet()
    {
        Console.WriteLine($"Hello, I am {Name}!");
    }
}

Adding a Constructor#

A constructor is a special method that runs when an object is created. It’s used to set the initial state of the object.

public class Player
{
    public string Name;

    public Player(string name)
    {
        Name = name;
    }
}

Creating an Object#

Use new followed by the class name and parentheses to create an instance.

Player player = new Player("Alice");
player.Greet();

Common Mistakes#

Missing the access modifier Omitting public doesn’t cause a compile error — C# defaults to internal — but the class may not be accessible where you need it. Be explicit: always include public for classes you intend to use across files.

Forgetting new when creating an object Player player = Player() is a compile error. The new keyword is required to create an instance.

Mismatched constructor parameters If the constructor expects a string name argument, calling new Player() without arguments is a compile error. The call must match the constructor signature exactly.

Naming the class differently from the file C# doesn’t require the filename and class name to match, but the convention is strong. A class called Player should live in Player.cs. Ignoring this makes the codebase harder to navigate.

Resources#