C# Classes and Objects: OOP Basics Explained with Examples
In C#, classes and objects are the foundation of Object-Oriented Programming (OOP). A class is a blueprint for creating objects, and an object is a real instance of that class.
Classes help you organize code into reusable, structured components instead of writing everything in a single block.
1. What is a Class in C#?
A class is a user-defined blueprint that defines:
• Properties (data)
• Methods (behavior)
It does not consume memory until an object is created from it.
Syntax:
class ClassName
{
// fields (variables)
// methods
}
2. What is an Object in C#?
An object is an instance of a class. It is a real entity created from the blueprint.
When you create an object:
• Memory is allocated
• You can access class members
3. Example: Class and Object in C#
using System;
class Car
{
public string brand = "Toyota";
public void Drive()
{
Console.WriteLine("Car is driving");
}
}
class Program
{
static void Main()
{
Car myCar = new Car(); // object creation
Console.WriteLine(myCar.brand);
myCar.Drive();
}
}
Output:
Toyota
Car is driving
4. Real-World Example
Think of a class as a car blueprint:
| Concept | Real World Example |
|---|---|
| Class | Car blueprint or design plan |
| Object | Actual car built from the blueprint |
| Property | Car attributes like color, brand, model |
| Method | Actions like drive, brake, accelerate |
| Memory Usage | Class does not use memory, object does |
5. Multiple Objects from Same Class
Car car1 = new Car();
Car car2 = new Car();
car1.brand = "BMW";
car2.brand = "Audi";
Each object has its own separate data.
6. Properties vs Fields (Simple Explanation)
• Field → simple variable inside class
• Property → controlled access to data (we will cover later in Encapsulation)
7. Why Use Classes and Objects?
Advantages:
• Code reusability
• Better organization
• Easy maintenance
• Real-world modeling
• Scalable applications
8. When to Use Classes?
Use classes when:
• You want to represent real-world entities (Car, User, Product)
• You need reusable logic
• You are building structured applications
9. Common Mistakes
• Forgetting to create an object
• Confusing class with object
• Putting everything in Main method
• Not using proper naming conventions
10. Best Practices
• Use PascalCase for class names (Car, UserAccount)
• Keep classes focused on one responsibility
• Avoid large classes with too many responsibilities
• Create meaningful object names
11. Class vs Object Summary
| Class | Object |
|---|---|
| Blueprint or template | Real instance of class |
| Does not occupy memory | Occupies memory |
| Defines structure | Stores actual data |
| Declared once | Can create multiple instances |