Classes & Objects in C#
Classes and Objects are fundamental concepts of Object-Oriented Programming (OOP) in C#. A class defines the structure and behavior of an object, while an object is an actual instance created from that class.
In simple words, a class can be considered a blueprint, and an object is a real instance created using that blueprint.
What is a Class?
A class is a user-defined type that groups related data and behavior together. Data can be represented using fields or properties, while behavior can be represented using methods.
A class does not represent one specific object. Instead, it defines what information an object should contain and what operations that object can perform.
public string Name;
public int Age;
public void DisplayDetails()
{
Console.WriteLine( $"Name: {Name}");
Console.WriteLine( $"Age: {Age}");
}
}
In this example, Student is a class. It contains Name and Age as data members and DisplayDetails() as a method.
What is an Object?
An object is an instance of a class. When an object is created, memory is allocated for that object and it can store its own values for the data defined by the class.
An object is generally created using the new keyword.
Here, student1 is a reference variable that refers to an object of the Student class.
Class vs Object
| Class | Object |
|---|---|
| A blueprint or definition. | An actual instance of a class. |
| Defines data and behavior. | Contains actual values and uses the defined behavior. |
| Does not represent one specific entity. | Represents a specific entity. |
| Example: Student | Example: student1 |
Basic Class Syntax
The general syntax for creating a class is:
// Fields
// Properties
// Methods
}
| Part | Purpose |
|---|---|
| class | Keyword used to declare a class. |
| ClassName | Name of the class. |
| Fields | Variables used to store data. |
| Properties | Members commonly used to expose and control access to data. |
| Methods | Define actions or behavior. |
Fields in a Class
A field is a variable declared inside a class. Fields can store information related to an object.
public int EmployeeId;
public string Name;
double Salary;
}
Here, EmployeeId, Name, and Salary are fields of the Employee class.
Properties in a Class
Properties provide a controlled way to expose data from a class. In modern C# applications, properties are commonly preferred over public fields.
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
}
The get accessor is used to retrieve a value and the set accessor is used to assign a value.
Methods Inside a Class
A class can contain methods that define the behavior of its objects.
public string Name { get; set; }
public void Study()
{
Console.WriteLine( $"{Name} is studying C#.");
}
}
Creating an Object
To create an object, use the class name followed by the object variable and the new keyword.
This statement creates a new object of the Student class.
Complete Class & Object Example
Let's create a complete example using a Student class.
using System;
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
public void DisplayDetails()
{
Console.WriteLine( $"Student Id: {Id}");
Console.WriteLine( $"Student Name: {Name}");
Console.WriteLine( $"Course: {Course}");
}
}
class Program
{
public static void Main()
{
Student student = new Student();
student.Id = 101;
student.Name = "Rahul";
student.Course = "C# Full Stack";
student.DisplayDetails();
}
}
Student Name: Rahul
Course: C# Full Stack
Understanding the Example
| Code | Explanation |
|---|---|
| class Student | Defines a class named Student. |
| Id | Property used to store student ID. |
| Name | Property used to store student name. |
| Course | Property used to store the course name. |
| DisplayDetails() | Method that displays student information. |
| new Student() | Creates an object of the Student class. |
| student.Name | Accesses the Name property of the object. |
| student.DisplayDetails() | Calls the method using the object. |
Creating Multiple Objects
A single class can be used to create multiple objects. Each object can contain its own data.
student1.Id = 101;
student1.Name = "Rahul";
student1.Course = "C#";
Student student2 = new Student();
student2.Id = 102;
student2.Name = "Priya";
student2.Course = "Java";
student1.DisplayDetails();
student2.DisplayDetails();
Here, student1 and student2 are two different objects of the same Student class. Each object has its own values.
Modifying Object Data
After creating an object, its properties can be changed when the properties allow assignment.
using System;
Console.WriteLine("Hello, World 🌍...!");
Accessing Class Members
The dot . operator is used to access properties, fields, and methods through an object.
student.Id
student.DisplayDetails();
In these examples, the dot operator is used to access members belonging to the student object.
Real-World Example: Employee
In a real-world application, we can create an Employee class containing employee information and behavior.
public int Id { get; set; }
public string Name { get; set; }
string Department { get; set; }
public void DisplayEmployee()
{
Console.WriteLine( $"Employee: {Name}");
Console.WriteLine( $"Department: {Department}");
}
}
The same concept is used in enterprise applications. For example, an application may contain classes such as Customer, Product, Order, Employee, and Payment.
Class Contains Data and Behavior
One of the important ideas of OOP is combining related data and behavior inside a class.
| Component | Example |
|---|---|
| Data | Name, Id, Salary |
| Properties | Name { get; set; } |
| Behavior | DisplayDetails(), CalculateSalary() |
Instance Members
Members that belong to a particular object are called instance members. Each object can have its own values for instance properties and fields.
public string Name { get; set; }
}
Student s1 = new Student();
Student s2 = new Student();
s1.Name = "Rahul";
s2.Name = "Priya";
s1 and s2 are different objects, so each object has its own Name value.
Instance vs Static Members
Instance members are accessed through an object, while static members belong to the class itself.
public int Add( int a, int b)
{
return a + b;
}
public static int Multiply( int a, int b)
{
return a * b;
}
}
Calculator calculator = new Calculator();
int result1 = calculator.Add(10, 20);
int result2 = Calculator.Multiply(10, 20);
Here, Add() is an instance method and requires an object. Multiply() is static and can be called using the class name.
Object Lifetime
An object exists while it is reachable by the application. When an object is no longer needed and becomes unreachable, it can eventually become eligible for Garbage Collection.
student.Name = "Rahul";
student = null;
After the reference is set to null, if no other references point to the object, that object can become eligible for garbage collection.
C# Naming Best Practices
- Use PascalCase for class names. Example: StudentDetails
- Use meaningful names that clearly describe the purpose of the class.
- Use meaningful property and method names.
- Keep a class focused on a clear responsibility.
- Avoid unnecessarily large classes containing unrelated responsibilities.
Common Beginner Mistakes
- Confusing a class with an object.
- Forgetting to use the new keyword when creating a normal class object.
- Trying to access instance members directly through the class name.
- Creating public fields when a property would be more appropriate.
- Giving classes unclear or meaningless names.
- Putting unrelated responsibilities into one class.
How Classes & Objects Are Used in Real Applications
In real-world C# and ASP.NET Core applications, classes are used everywhere. Developers create classes to represent business entities, services, models, repositories, controllers, and other components.
| Class | Possible Responsibility |
|---|---|
| Student | Student information and operations. |
| Employee | Employee details and related operations. |
| Product | Product information and pricing. |
| Order | Customer order information. |
| Customer | Customer details and related behavior. |
CIIT Practical Point
In professional C# development, understanding classes and objects is essential because most applications are designed using object-oriented principles.
In ASP.NET Core applications, you will work with classes for models, controllers, services, repositories, DTOs, and business logic.
A strong understanding of classes and objects makes it easier to understand important OOP concepts such as Encapsulation, Inheritance, Polymorphism, and Interfaces.
CIIT Interview Points
- What is a class in C#?
- What is an object?
- What is the difference between a class and an object?
- How do you create an object in C#?
- What is the purpose of the new keyword?
- What are fields, properties, and methods?
- What is an instance member?
- What is a static member?
- Can multiple objects be created from one class?
Summary
- A class is a blueprint or definition for objects.
- An object is an instance of a class.
- A class can contain fields, properties, and methods.
- Objects are commonly created using the new keyword.
- Multiple objects can be created from the same class.
- Each object can maintain its own instance data.
- Instance members are accessed through objects.
- Classes and objects form the foundation of Object-Oriented Programming in C#.
Practice Questions
- Create a class named Student.
- Add Id, Name, and Course properties to the class.
- Create a method named DisplayDetails().
- Create two Student objects with different values.
- Display the details of both students.
- Create an Employee class with Id, Name, Department, and Salary.
- Create an object of Employee and display its details.
- Explain the difference between a class and an object.