Codectionary / Developer documentation / C#

Classes & Objects

A class is a blueprint for creating objects, bundling related data (fields/properties) and behavior (methods) together. C# is a fully object-oriented language - every application has at least one class, typically with a Main method as its entry point. An object is a specific instance of a class, created with the new keyword, with its own independent copy of the class's instance data.

Syntax

public class ClassName {\n  // fields, properties, methods\n}

Examples

Basic Class Definition

Creating a simple class with fields, a constructor, and a method.

public class Person
{
    public string Name;
    public int Age;

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void Introduce()
    {
        Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
    }
}

// Usage
Person person = new Person("Alice", 25);
person.Introduce();

Creating Multiple Independent Objects

Each object created from a class has its own separate copy of instance data.

Person alice = new Person("Alice", 25);
Person bob = new Person("Bob", 30);

alice.Age = 26;  // only affects alice, not bob

Console.WriteLine($"{alice.Name}: {alice.Age}");  // Alice: 26
Console.WriteLine($"{bob.Name}: {bob.Age}");        // Bob: 30

Static Members

static fields and methods belong to the class itself, shared across all instances rather than being per-object.

public class Counter
{
    private static int count = 0;  // shared across all instances
    public int InstanceId;

    public Counter()
    {
        count++;
        InstanceId = count;
    }

    public static int GetCount() => count;
}

Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

Console.WriteLine($"Total instances: {Counter.GetCount()}");  // 3
Console.WriteLine($"c2 ID: {c2.InstanceId}");                   // 2

Object Initializers

A concise syntax for setting properties immediately when creating an object.

public class Product
{
    public string Name { get; set; } = "";
    public double Price { get; set; }
}

Product laptop = new Product
{
    Name = "Laptop",
    Price = 999.99
};

Console.WriteLine($"{laptop.Name}: ${laptop.Price}");

Best practices

  • Use meaningful, PascalCase class names that describe what the class represents (Customer, not customer or CustomerClass)
  • Prefer properties (get/set) over public fields for exposing data - it gives you a way to add validation later without breaking callers
  • Write one class per file, with the filename matching the public class name, matching standard C# project conventions
  • Follow the Single Responsibility Principle - each class should have one clear, well-defined purpose

At a glance

Purpose
Applications on the .NET platform
File extension
.cs
Runs in
.NET runtime
Usually used with
.NET SDK and libraries

Specifications & further reading

Related C# documentation

Constructors
A constructor is a special method that runs automatically when an object is created with new, used to initialize the object's state. A constructor shares its name with the class and has no return type. C# supports constructor overloading (multiple constructors with different parameter lists) and constructor chaining with this(...), where one constructor calls another in the same class to avoid duplicating initialization logic.
Properties (get/set)
Properties are C#'s idiomatic way to expose class data through accessor-like syntax while still allowing controlled access via get and set. Unlike a plain public field, a property can validate a value before it's set, compute a value on the fly, or restrict access to read-only. Auto-implemented properties (using { get; set; } with no body) provide a concise shorthand when no custom logic is needed.
Access Modifiers
Access modifiers control the visibility of classes, fields, methods, and properties from other parts of a program. C# provides public (accessible from anywhere), private (accessible only within the declaring class - the default for class members), protected (accessible within the class and its subclasses), internal (accessible only within the same assembly/project), and combinations like protected internal and private protected.
Inheritance & base
Inheritance lets a class (the derived or child class) reuse and extend the members of another class (the base or parent class), written as class Child : Parent. The base keyword gives access to the parent class's members from within the child, most commonly used to call the parent's constructor so the child doesn't have to duplicate its setup logic. Unlike some languages, C# only supports single class inheritance - a class can extend just one base class, but can implement multiple interfaces.