AnyCompiler

Classes and Objects

A class groups related fields under a named type, and a constructor is a special method, named after the class, that runs automatically whenever you create a new instance with new.

using System;

class Dog {
    public string Name;
    public int Age;

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

class Program {
    static void Main() {
        Dog d = new Dog("Rex", 3);
        Console.WriteLine(d.Name + " is " + d.Age);
    }
}
Output
Rex is 3

Next: properties — C#'s first-class get/set syntax, genuinely distinctive compared to every other class-based language on this site.

Practice exercise

Define a class Book with fields Title (string) and Pages (int). Create a Book with Title "Dune" and Pages 412, then print both with Console.WriteLine.