Chapter 9: Classes and Objects
1. What is a Class? (Super Simple Analogy)
Think of a class like a blueprint or cookie cutter:
- The class defines what something looks like and what it can do.
- An object is an actual thing you create using that blueprint (like an actual cookie made from the cookie cutter).
Example:
- Class = Car (blueprint: has color, model, speed, can drive, can honk…)
- Object = myToyota, yourTesla, friend’sMaruti (actual cars made from the Car blueprint)
2. Defining a Simple Class
Let’s create our first class!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// This is a class definition class Person { // Fields (private data – like internal storage) private string name; private int age; // Constructor (special method that runs when we create an object) public Person(string personName, int personAge) { name = personName; age = personAge; } // Method (what the object can do) public void Introduce() { Console.WriteLine($"Hi! My name is {name} and I am {age} years old. Nice to meet you! 😊"); } } |
How to use it (create objects):
|
0 1 2 3 4 5 6 7 8 9 10 11 |
// Create objects (instances) of the Person class Person webliance = new Person("Webliance", 25); Person rahul = new Person("Rahul", 28); webliance.Introduce(); // Output: Hi! My name is Webliance and I am 25 years old... rahul.Introduce(); // Output: Hi! My name is Rahul and I am 28 years old... |
3. Fields vs Properties (Very Important Difference!)
Fields → private variables that store data (usually hidden)
Properties → public way to get and set fields (with control)
There are two main types of properties in 2026 C#:
A. Auto-implemented Properties (Most Common – Super Clean!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
class Person { // Auto-implemented properties (compiler creates hidden field for you) public string Name { get; set; } public int Age { get; set; } public string City { get; set; } = "Hyderabad"; // Default value! } |
B. Full Properties (When you want control / validation)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Person { private string _name; private int _age; public string Name { get => _name; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Name cannot be empty!"); _name = value.Trim(); } } public int Age { get => _age; set { if (value < 0 || value > 120) throw new ArgumentException("Age must be between 0 and 120!"); _age = value; } } public string Introduce() => $"Hi! I'm {_name}, {_age} years old from Hyderabad!"; } |
4. Constructors – How Objects Are Born
A constructor is a special method that runs automatically when you create an object with new.
A. Default Constructor (No Parameters)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Person { public string Name { get; set; } public int Age { get; set; } // Default constructor public Person() { Name = "Unknown"; Age = 0; } } Person p = new Person(); // Uses default constructor |
B. Parameterized Constructor (Most Useful)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
public Person(string name, int age) { Name = name; Age = age; } Person webliance = new Person("Webliance", 25); |
C. Static Constructor (Rare – Runs Once Per Class)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Logger { public static int LogCount { get; private set; } // Static constructor – runs only once when class is first used static Logger() { LogCount = 0; Console.WriteLine("Logger class is ready! 📝"); } public void Log(string message) { LogCount++; Console.WriteLine($"[{LogCount}] {message}"); } } |
5. Object Initialization Syntax (Modern & Very Clean – C# 3+)
You can set properties right after new without calling a constructor!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Old long way Person p1 = new Person(); p1.Name = "Priya"; p1.Age = 22; p1.City = "Hyderabad"; // Modern beautiful way var p2 = new Person { Name = "Priya", Age = 22, City = "Hyderabad" }; // With constructor + initialization var p3 = new Person("Amit", 27) { City = "Bangalore" }; |
6. Mini-Project: Bank Account Class
Let’s build something real!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
class BankAccount { // Auto-implemented properties public string AccountHolder { get; set; } public string AccountNumber { get; } public decimal Balance { get; private set; } // Only class can change balance // Constructor public BankAccount(string holder, string accNumber, decimal initialDeposit = 0) { AccountHolder = holder; AccountNumber = accNumber; Balance = initialDeposit >= 0 ? initialDeposit : 0; } // Methods public void Deposit(decimal amount) { if (amount <= 0) throw new ArgumentException("Deposit must be positive!"); Balance += amount; Console.WriteLine($"Deposited ₹{amount:N2}. New balance: ₹{Balance:N2}"); } public void Withdraw(decimal amount) { if (amount <= 0) throw new ArgumentException("Withdrawal must be positive!"); if (amount > Balance) throw new InvalidOperationException("Insufficient funds!"); Balance -= amount; Console.WriteLine($"Withdrew ₹{amount:N2}. New balance: ₹{Balance:N2}"); } public void ShowInfo() { Console.WriteLine($"Account: {AccountNumber} | Holder: {AccountHolder} | Balance: ₹{Balance:N2}"); } } // Usage var myAccount = new BankAccount("Webliance", "1234567890", 5000); myAccount.ShowInfo(); // Balance: ₹5,000.00 myAccount.Deposit(10000); // Deposited ₹10,000.00 myAccount.Withdraw(3000); // Withdrew ₹3,000.00 myAccount.ShowInfo(); // Balance: ₹12,000.00 |
Summary – What We Learned Today
- Class = blueprint
- Object = instance created with new
- Fields → private data
- Properties → public access (auto or full)
- Constructors → default, parameterized, static
- Object initializer → { Property = value } syntax
Your Homework (Super Fun & Practical!)
- Create a new console project called OOPBasics
- Create a class called Car with:
- Properties: Make, Model, Year, Color, CurrentSpeed (private set)
- Constructor that takes Make, Model, Year, Color
- Method Accelerate(int speedIncrease)
- Method Brake(int speedDecrease)
- Method ShowStatus() → “My Toyota Corolla (2023, Red) is going 80 km/h”
- In Program.cs, create 2–3 cars, accelerate them, brake one, and show their status
Next lesson: Methods in Depth – parameters, overloading, ref/out, optional parameters – we’re going to make objects do even more amazing things!
You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with constructors or properties? Just tell me — I’m right here for you! 💙
