OOP: Classes & Objects
C# is a strictly object-oriented language. In this lesson, we will look at classes, instances, constructors, and modern C# Properties.
1 Auto-Implemented Properties ({ get; set; })
In C#, rather than writing verbose getter and setter methods, you can use **Auto-Implemented Properties**. The compiler automatically generates the private backing fields, getters, and setters for you behind the scenes, making your code significantly cleaner:
public string Name { get; set; } // Shorthand property
2 Classes Code
Let's run a program declaring classes, constructor chaining, and shorthand properties:
C# — Classes and Objects
▶ Run Code
using System;
class Car {
// Auto-implemented properties
public string Model { get; set; }
public int Year { get; set; }
// Constructor
public Car(string model, int year) {
Model = model;
Year = year;
}
// Chained constructor using 'this'
public Car(string model) : this(model, 2026) {}
public void ShowInfo() {
Console.WriteLine($"Model: {Model}, Year: {Year}");
}
}
class Program {
static void Main() {
Car car1 = new Car("Ford Mustang", 2022);
Car car2 = new Car("Tesla Model Y");
car1.ShowInfo();
car2.ShowInfo();
}
}
3 Code Challenge
Challenge: Create a class called `Student` with properties `Name` (string) and `Gpa` (double). Implement a constructor. Instantiate a student, assign values, and print their details.