C#

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.

Constructor (C#)

A constructor in C# is a special method inside a class that runs automatically when you create an object with new.

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

Defining a Constructor#

A constructor has the same name as the class and no return type — not even void.

public class Player
{
    public string Name;

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

Name = name stores the argument on the object so it’s available later.

Method (C#)

A method in C# is a function defined inside a class that defines what an object can do.

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

Defining a Method#

A C# method has an access modifier, a return type, a name, and a body.

public void Greet()
{
    Console.WriteLine("Hello!");
}
  • public — the access modifier; public means the method can be called from anywhere
  • void — the return type; void means the method returns nothing
  • Greet — the method name; use PascalCase by convention
  • () — the parameter list; empty here, but arguments go inside these parentheses

Return Types#

If a method produces a value, declare the return type instead of void and use return to send it back.

Property (C#)

A property in C# is a member of a class that provides controlled access to a value. It looks like a variable when you use it, but it’s backed by get and set accessors that control how the value is read and written.

Auto-Property#

The simplest form is the auto-property. The compiler generates the backing storage automatically.

public class Player
{
    public int WinCount { get; set; }
}
  • get — allows the value to be read
  • set — allows the value to be written

Using it looks exactly like using a variable: