C-SHARP - 3.2 Object and class

C# is an object-oriented language: almost everything we manipulate is an object. To create our own objects we first define what they look like with a class. A class is a blueprint declared once that can be instantiated as many times as we need with different values. Each instance shares the same structure but holds its own data, which is perfect for representing things like cars, users or products in our applications.

To make this concrete, imagine running a car garage. Every car has common characteristics with different values: a colour that varies from one car to another, a number of doors that can be 3, 4 or 5, a brand, a year. In the class we describe these properties and call them attributes. Starting from this single class, we can create several instances sharing the same attributes but with their own values: one car may be a 2019 blue Peugeot, another a 2021 grey Mercedes, and so on.

Classes also contain methods

  • Attributes describe the state of the object (brand, year, colour).
  • Methods describe what the object can do (drive, accelerate, brake).
  • An instance is a concrete object built from the class with its own data.

Methods are functions that belong to the class and let us act on the instance: for a car class we could write Drive, Accelerate or Reverse. Beyond modelling real-world entities, object-oriented programming helps us organise code, avoid repetition and build reusable building blocks. Instead of repeating fifty almost-identical blocks of code to handle many cars, we declare a single class and produce as many instances as we need with one line of code each. In the next video we open Visual Studio to see how to declare a class in C# and create our first instance.