← C# from Scratch Lesson 28 of 39 · 10 XP

Classes and objects

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

using System;

Car a = new Car();         // new creates an object in memory
a.Model = "Mustang";
a.Year = 1969;
a.Honk();

Car b = a;                 // b is a SECOND REFERENCE to the same object, not a copy!
b.Year = 2024;
Console.WriteLine(a.Year); // 2024

class Car
{
    public string Model;   // fields — the object's data
    public int Year;

    public void Honk()     // a method — without static: it works with a specific object
    {
        Console.WriteLine($"{Model} {Year}: Beep!");
    }
}

Classes are declared after the top-level statements. Inside a method, the fields of its own object are available simply by name (or through this.Model).

Task. Finish the Counter class: a field public int Value, and methods Inc() (+1), Add(int n) (+n) and Reset() (to 0). The program reads commands (inc, add N, reset) until the end of the input and prints Value.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.