Classes and objects are the foundation of object oriented programming in C#. If variables store data and methods store behavior, classes help us combine related data and behavior into one meaningful unit. This makes large programs easier to organize, understand, reuse, and maintain.
A class is like a blueprint. It describes what something should contain and what it should be able to do. An object is a real instance created from that blueprint. For example, Car can be a class, and myCar can be an object created from that class.
In C#, almost every serious application uses classes. Desktop apps, web APIs, games, mobile apps, backend services, and embedded tools written with .NET all use classes to model real data and real behavior.
What Is a Class in C#?
A class in C# is a user defined type that groups fields, properties, methods, constructors, and other members. It defines the structure and behavior of objects that will be created from it.
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
Here, Student is a class. It contains two properties, Name and Age, and one method named DisplayInfo. The class does not automatically represent one particular student. It only describes what a student object should look like.
What Is an Object in C#?
An object is an instance of a class. When you create an object, memory is allocated for that object, and you can store actual values inside it. Objects are created using the new keyword.
Student student1 = new Student();
student1.Name = "Aarav";
student1.Age = 20;
student1.DisplayInfo();
In this example, student1 is an object of the Student class. The class defines the structure, but the object holds the real values. If you create another object from the same class, it gets its own separate data.
Student student2 = new Student();
student2.Name = "Meera";
student2.Age = 22;
student2.DisplayInfo();
Both student1 and student2 are created from the same class, but their values are different. This is the main power of classes and objects: one design can create many independent instances.
Class vs Object in C#
| Point | Class | Object |
|---|---|---|
| Meaning | A blueprint or template | A real instance created from a class |
| Memory | Does not store instance values by itself | Stores actual values in memory |
| Example | Student | student1, student2 |
| Purpose | Defines structure and behavior | Uses structure and behavior with real data |
| Creation | Declared using the class keyword | Created using the new keyword |
A simple way to remember it is this: a class is the plan, and an object is the thing built from that plan.
Syntax of a Class in C#
The basic syntax of a class starts with an access modifier, the class keyword, and the class name.
accessModifier class ClassName
{
// fields
// properties
// methods
// constructors
}
For beginner level code, you will often see classes declared as public, internal, or without an explicit access modifier. Access modifiers control where the class and its members can be used. We will handle access modifiers separately in detail, but for now remember that public means accessible from outside.
Fields, Properties, and Methods
A useful class usually has three important parts: fields, properties, and methods.
- Fields store data directly inside the object.
- Properties provide controlled access to data.
- Methods define actions or behavior.
class BankAccount
{
private decimal balance;
public string AccountHolder { get; set; }
public void Deposit(decimal amount)
{
if (amount > 0)
{
balance += amount;
}
}
public decimal GetBalance()
{
return balance;
}
}
In this example, balance is a field, AccountHolder is a property, and Deposit plus GetBalance are methods. The class protects the balance by keeping it private. Instead of changing the balance directly, outside code must call a method.
Creating Objects with new Keyword
The new keyword creates an object from a class. It calls the constructor of the class and returns a reference to the new object.
BankAccount account = new BankAccount();
account.AccountHolder = "Riya";
account.Deposit(5000);
Console.WriteLine(account.GetBalance());
The variable account does not contain the whole object directly. It stores a reference to the object. The actual object lives on the managed heap, and the .NET runtime manages its lifetime through garbage collection.
Multiple Objects from One Class
A class can create many objects. Each object has its own copy of instance fields and properties. Changing one object does not automatically change another object.
BankAccount account1 = new BankAccount();
account1.AccountHolder = "Riya";
account1.Deposit(5000);
BankAccount account2 = new BankAccount();
account2.AccountHolder = "Karan";
account2.Deposit(12000);
Console.WriteLine(account1.GetBalance());
Console.WriteLine(account2.GetBalance());
Both objects use the same class design, but they hold different values. This is why classes are used heavily in business applications. You can create one class named Customer and then create thousands of customer objects from it.
Reference Type Behavior
Classes in C# are reference types. This means a variable of a class type usually stores a reference to an object, not the object data itself. If you assign one object variable to another, both variables can point to the same object.
Student first = new Student();
first.Name = "Aarav";
Student second = first;
second.Name = "Changed Name";
Console.WriteLine(first.Name);
The output will show Changed Name. This happens because first and second refer to the same object. This behavior is important when passing objects to methods, storing objects in collections, or sharing data between parts of a program.
Instance Members and Static Members
Members that belong to a specific object are called instance members. Members that belong to the class itself are called static members. You access instance members through an object, and static members through the class name.
class Counter
{
public int Value { get; set; }
public static int ObjectCount { get; private set; }
public Counter()
{
ObjectCount++;
}
}
Each Counter object has its own Value. But ObjectCount belongs to the class, so it is shared. Static members are useful for common values, helper methods, configuration, factory methods, and counters. They should not be used as a shortcut for everything because shared state can make code harder to test and debug.
Constructors in Classes
A constructor is a special method that runs when an object is created. It is commonly used to initialize object data. The constructor name must match the class name.
class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
}
Product laptop = new Product("Laptop", 55000);
This constructor forces the caller to provide a product name and price when creating the object. Constructors are powerful, but they should not do too much work. Their main job is to create a valid object state.
Encapsulation with Classes
Encapsulation means hiding internal details and exposing only safe operations. A class should not blindly expose every field. Instead, it should protect its internal state and provide clear ways to use the object.
class TemperatureSensor
{
private double temperatureCelsius;
public double TemperatureCelsius
{
get { return temperatureCelsius; }
set
{
if (value >= -273.15)
{
temperatureCelsius = value;
}
}
}
}
The class does not allow a temperature below absolute zero. This is better than using a public field because the class can protect its own rules. Good object oriented code is not only about creating classes; it is about creating classes that keep data valid.
Real World Example of Classes and Objects
Suppose you are building a small order system. You may create classes such as Customer, Product, Order, and Payment. Each class represents one concept in the system.
class Order
{
public int OrderId { get; set; }
public string CustomerName { get; set; }
public decimal TotalAmount { get; set; }
public void PrintReceipt()
{
Console.WriteLine($"Order: {OrderId}");
Console.WriteLine($"Customer: {CustomerName}");
Console.WriteLine($"Total: {TotalAmount}");
}
}
This class keeps order related data and behavior in one place. Instead of passing separate variables everywhere, the program can pass an Order object. This improves readability and reduces mistakes.
Common Mistakes with Classes and Objects
- Creating classes with no clear responsibility.
- Making every field public instead of using properties or methods.
- Putting unrelated logic inside one large class.
- Using static members when object based design is better.
- Forgetting that class variables hold references, not full object copies.
- Creating objects before understanding what data each object should own.
A class should represent one meaningful concept. If a class becomes a dumping ground for unrelated methods, it becomes hard to test and hard to change. Smaller, focused classes usually create cleaner programs.
Best Practices for Classes in C#
- Use clear class names such as
Customer,Invoice,SensorReading, orEmailService. - Keep fields private unless there is a strong reason not to.
- Use properties for controlled access to data.
- Keep methods focused on one task.
- Initialize required data through constructors.
- Avoid large classes that try to manage the whole program.
- Use static members only when the member truly belongs to the class and not to one object.
Classes and Objects Interview Points
For interviews and exams, remember these points clearly. A class is a blueprint, an object is an instance, and classes in C# are reference types. Objects are created using new. Instance members belong to objects, while static members belong to the class. Encapsulation helps protect internal data and expose safe behavior.
Also remember that C# supports object oriented features such as inheritance, polymorphism, abstraction, encapsulation, interfaces, abstract classes, properties, constructors, and access modifiers. Classes are the base structure that connects all these concepts together.
FAQs on Classes and Objects in C#
Is a class an object in C#?
No. A class is a blueprint, while an object is an instance created from that blueprint. The class defines members, and the object stores actual values.
Can one class create multiple objects?
Yes. One class can create any number of objects. Each object has its own instance data unless the member is static.
Are classes value types or reference types in C#?
Classes are reference types in C#. Variables of a class type store references to objects. Structs are usually used when value type behavior is required.
What is the difference between a field and a property?
A field stores data directly. A property provides controlled access to data and can include validation, computed values, or restricted setters.
Continue learning C# in order
Follow the topic sequence with the previous and next lesson.