Skip to content

Classes & Objects

Classes are the fundamental building blocks of object-oriented programming in C#. They serve as blueprints for creating objects, encapsulating data and behavior into a single unit. Objects are instances of classes that contain both the data and the methods that operate on that data.

Class Definition

A class definition includes properties to store data, constructors to initialize objects, and methods to define behavior. This structure helps organize code and maintain encapsulation.

csharp
public class Person
{
    // Properties
    public string Name { get; set; }
    public int Age { get; set; }

    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // Method
    public void Introduce()
    {
        Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
    }
}

Inheritance

Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. This promotes code reuse and establishes relationships between classes.

csharp
public class Employee : Person
{
    public string Department { get; set; }

    public Employee(string name, int age, string department) 
        : base(name, age)
    {
        Department = department;
    }
}

Interfaces

Interfaces define contracts that classes can implement, ensuring consistent behavior across different classes. They provide a way to achieve abstraction and polymorphism.

csharp
public interface IPayable
{
    decimal CalculatePay();
}

public class Employee : Person, IPayable
{
    public decimal CalculatePay()
    {
        return 1000m;
    }
}