Think of a class as a blueprint and an object as the actual thing you build from that blueprint. You've been using classes all along โ Console is a class, string is a class. Now it's time to make your own.
Your First Class
A class bundles data (fields) and behavior (methods) together. Use the class keyword, give it a name, and you're off.
class Car
{
string brand;
int year;
void Honk()
{
Console.WriteLine("Beep beep!");
}
}
This defines what a Car is โ it has a brand, a year, and it can honk. But it doesn't exist yet. You need to create an actual car object.
Creating Objects with new
The new keyword brings your blueprint to life. It allocates memory and gives you back a reference to the object.
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2022;
myCar.Honk();
You declare a variable of type Car, then assign it a new Car instance. The dot operator (.) lets you access fields and call methods on that object.
Access Modifiers
By default, class members are private โ only code inside the class can see them. Use public to make them accessible from outside.
class Car
{
public string brand;
public int year;
public void Honk()
{
Console.WriteLine("Beep beep!");
}
}
Without public, you'd get a compile error trying to access brand or call Honk() from Main.
Multiple Objects
You can create as many objects from one class as you want. Each one has its own copy of the fields.
Car car1 = new Car();
car1.brand = "Honda";
Car car2 = new Car();
car2.brand = "Ford";
Console.WriteLine(car1.brand);
Console.WriteLine(car2.brand);