Classes & Objects in C#

A class is the design sheet for a car. Objects are the actual cars built from it.

60-Second Version: Class = design of a car. Object = real car you drive. Use new to build it.

1. The Design Sheet = Class

A class defines what data and actions every car will have. No real car exists yet.

public class Car
{
    public string Owner; // Data: Every car has an owner
    private int engineNumber; // Data: Hidden from outside
    
    public void Start() // Action: Every car can start
    { 
        Console.WriteLine($"{Owner}'s car started"); 
    }
}

2. Build the Real Car = Object

new takes the design and builds 1 real car in memory.

Car kunalCar = new Car(); 
kunalCar.Owner = "Kunal"; // OK: Owner is public
// kunalCar.engineNumber = 1; // Error: engineNumber is private
kunalCar.Start();

3. Access Control: public vs private

public = Anyone can use it. private = Only code inside the class can use it. Default is private for fields.

Beginner Trap: Car c; c.Start(); crashes with NullReferenceException. You drew the design but never built the car with new.

Quick Check ๐Ÿง 

Next: Inheritance - Building a SportsCar from Car using protected members.

Comments on Classes & Objects (0)

No comments yet. Be the first to share your thoughts!