C# Classes
Building blocks of object-oriented programming
📚 What are Classes?
A class is a blueprint for creating objects. It defines properties and methods that objects will have. Think of it as a template or recipe for making objects.
// Simple class definition
class Person
{
public string Name;
public int Age;
}
Class Components
Fields
Variables that store data
class Car
{
public string color;
public int year;
}
Methods
Functions that define behavior
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
Properties
Controlled access to fields
class Student
{
public string Name { get; set; }
}
Constructors
Initialize objects when created
class Book
{
public Book(string title)
{
Title = title;
}
}
🔹 Creating a Simple Class
A class is a blueprint for creating objects, defined using the class keyword followed by a PascalCase name like 'Dog'. This blueprint combines data (fields like Name, Breed, Age) and behavior (methods like Bark, DisplayInfo) into a single, cohesive unit. The definition establishes the structure and capabilities that every object of this type will possess. By following naming conventions and logically grouping related members, you create reusable, maintainable, and self-documenting code components that form the foundation of object-oriented design in C# and other modern programming languages.
class Dog
{
// Fields (data)
public string Name;
public string Breed;
public int Age;
// Method (behavior)
public void Bark()
{
Console.WriteLine(Name + " says: Woof!");
}
public void DisplayInfo()
{
Console.WriteLine("Name: " + Name);
Console.WriteLine("Breed: " + Breed);
Console.WriteLine("Age: " + Age);
}
}
Explanation:
This Dog class has three fields (Name, Breed, Age) and two methods (Bark, DisplayInfo).
🔹 Using a Class
To use a class, you instantiate an object using the new keyword, which allocates memory and calls the constructor. Each object, like the dog "Buddy", is a distinct instance with its own set of field values ("Golden Retriever", Age 3). You can then call the object's methods, such as Bark() which outputs "Woof!". This process of instantiation transforms the abstract class blueprint into a concrete, usable entity in your program. It encapsulates state and behavior, allowing you to model and interact with complex real-world concepts in a structured way.
class Program
{
static void Main()
{
// Create an object of Dog class
Dog myDog = new Dog();
// Set field values
myDog.Name = "Buddy";
myDog.Breed = "Golden Retriever";
myDog.Age = 3;
// Call methods
myDog.Bark();
myDog.DisplayInfo();
}
}
Output:
Buddy says: Woof!
Name: Buddy
Breed: Golden Retriever
Age: 3
🔹 Multiple Objects
A single class can generate numerous independent objects, each maintaining its own unique state. For example, from a 'Car' class, you can instantiate one object representing a "2020 Toyota Camry" and another for a "2021 Honda Civic". Although both objects share the same underlying structure (fields like make, model, year) and capabilities (methods), their internal data is separate. This principle is fundamental to OOP, enabling you to create scalable applications that manage collections of entities efficiently, such as lists of users, products, or game characters, all from one defined template.
class Car
{
public string Brand;
public string Model;
public int Year;
public void DisplayCar()
{
Console.WriteLine(Year + " " + Brand + " " + Model);
}
}
// Create multiple car objects
Car car1 = new Car();
car1.Brand = "Toyota";
car1.Model = "Camry";
car1.Year = 2020;
Car car2 = new Car();
car2.Brand = "Honda";
car2.Model = "Civic";
car2.Year = 2021;
car1.DisplayCar();
car2.DisplayCar();
Output:
2020 Toyota Camry
2021 Honda Civic
🔹 Class with Methods
Methods empower classes by defining the specific actions and operations objects can execute. A 'Calculator' class, for instance, might include methods like Add, Subtract, Multiply, and Divide. When called with parameters (e.g., 5 and 3), these methods perform their logic and return results (8, 2, 15, 2.5). Methods can manipulate internal object data, interact with other objects, or provide computational services. Well-designed methods are focused, perform a single task, and make class functionality intuitive and accessible, driving the interactive behavior of your application.
class Calculator
{
public int Add(int num1, int num2)
{
return num1 + num2;
}
public int Subtract(int num1, int num2)
{
return num1 - num2;
}
public int Multiply(int num1, int num2)
{
return num1 * num2;
}
public double Divide(int num1, int num2)
{
if (num2 != 0)
return (double)num1 / num2;
else
return 0;
}
}
// Usage
Calculator calc = new Calculator();
Console.WriteLine("5 + 3 = " + calc.Add(5, 3));
Console.WriteLine("5 - 3 = " + calc.Subtract(5, 3));
Console.WriteLine("5 * 3 = " + calc.Multiply(5, 3));
Console.WriteLine("5 / 2 = " + calc.Divide(5, 2));
Output:
5 + 3 = 8
5 - 3 = 2
5 * 3 = 15
5 / 2 = 2.5
🔹 Class Naming Conventions
Best Practices:
- PascalCase: Start with uppercase letter (e.g., MyClass, StudentRecord)
- Descriptive Names: Use meaningful names (e.g., BankAccount, not BA)
- Singular Nouns: Use singular form (e.g., Car, not Cars)
- Avoid Abbreviations: Write full words for clarity
- One Class Per File: Keep each class in its own file
🔹 Real-World Example
Interfaces enable dependency injection and loosely coupled architectures. In payment processing, an IPaymentGateway interface allows switching between CreditCardProcessor or PayPalProcessor without changing core logic. The system validates and processes payments through the interface, adhering to the Open/Closed Principle. This makes applications testable, maintainable, and adaptable to new payment methods.
class BankAccount
{
public string AccountNumber;
public string Owner;
public decimal Balance;
public void Deposit(decimal amount)
{
Balance += amount;
Console.WriteLine("Deposited: $" + amount);
Console.WriteLine("New Balance: $" + Balance);
}
public void Withdraw(decimal amount)
{
if (amount <= Balance)
{
Balance -= amount;
Console.WriteLine("Withdrawn: $" + amount);
Console.WriteLine("New Balance: $" + Balance);
}
else
{
Console.WriteLine("Insufficient funds!");
}
}
}
// Usage
BankAccount account = new BankAccount();
account.AccountNumber = "123456";
account.Owner = "John Doe";
account.Balance = 1000;
account.Deposit(500);
account.Withdraw(200);
Output:
Deposited: $500
New Balance: $1500
Withdrawn: $200
New Balance: $1300