C# Classes and Objects

In C#, a class is a blueprint or template used to define the structure and behavior of objects. An object is an instance of a class. Objects contain real data and interact with other objects through methods and properties. C# is an object-oriented programming language, which means almost everything in C# is an object.

1. Understanding Classes and Objects

A class serves as a template that defines the attributes (fields) and behaviors (methods) of an object. An object, in turn, is a specific instantiation of a class that holds real data. Let’s explore how this works:


class Car
{
    // Fields (Attributes)
    public string Make;
    public string Model;
    public int Year;

    // Constructor (Initializes fields)
    public Car(string make, string model, int year)
    {
        Make = make;
        Model = model;
        Year = year;
    }

    // Method (Behavior)
    public void DisplayDetails()
    {
        Console.WriteLine($"Car Details: {Year} {Make} {Model}");
    }
}

// Creating objects
Car myCar = new Car("Honda", "Civic", 2022);
Car yourCar = new Car("Tesla", "Model 3", 2023);

// Using methods
myCar.DisplayDetails();  // Output: Car Details: 2022 Honda Civic
yourCar.DisplayDetails(); // Output: Car Details: 2023 Tesla Model 3
    

2. Properties and Methods

A class defines properties (fields) that represent the attributes of the object and methods that define its behavior. For example, in the Car class above, Make, Model, and Year are properties, while DisplayDetails() is a method that prints the details of the car.


class Car
{
    public string Make;
    public string Model;
    public int Year;

    // Method to Start Engine
    public void StartEngine()
    {
        Console.WriteLine($"{Make} engine started.");
    }

    // Method to Stop Engine
    public void StopEngine()
    {
        Console.WriteLine($"{Make} engine stopped.");
    }
}

// Creating an object and calling methods
Car myCar = new Car { Make = "BMW", Model = "X5", Year = 2023 };
myCar.StartEngine();  // Output: BMW engine started.
myCar.StopEngine();   // Output: BMW engine stopped.
    

3. Constructors and Destructors

A constructor is a special method that initializes an object when it is created. A destructor is a special method that is invoked when an object is destroyed or goes out of scope. While constructors are used to initialize objects, destructors are used to clean up resources.

Constructor

Constructors allow you to set the initial state of an object. You can define multiple constructors with different parameters for flexibility.


class Car
{
    public string Make;
    public string Model;
    public int Year;

    // Constructor with parameters
    public Car(string make, string model, int year)
    {
        Make = make;
        Model = model;
        Year = year;
    }

    public void DisplayDetails()
    {
        Console.WriteLine($"Car Details: {Year} {Make} {Model}");
    }
}

// Using the constructor
Car myCar = new Car("Ford", "Mustang", 2022);
myCar.DisplayDetails();  // Output: Car Details: 2022 Ford Mustang
    

Destructor

In C#, destructors are not commonly used. They are invoked automatically when an object is garbage collected. Destructors are generally used for cleanup operations like closing file streams, releasing database connections, etc.


class Car
{
    public string Make;

    // Constructor
    public Car(string make)
    {
        Make = make;
    }

    // Destructor
    ~Car()
    {
        Console.WriteLine($"The {Make} car is being destroyed.");
    }
}

// Create and destroy object
Car myCar = new Car("Chevy");
    

4. Access Modifiers

Access modifiers determine how the members of a class can be accessed. In C#, there are several access modifiers:

  • public: The member is accessible from anywhere.
  • private: The member is only accessible within the class.
  • protected: The member is accessible within the class and its derived classes.
  • internal: The member is accessible within the same assembly.
  • protected internal: The member is accessible within the same assembly and derived classes.


class Car
{
    private string model;  // Private field

    // Public property
    public string Make { get; set; }

    // Constructor
    public Car(string make, string model)
    {
        Make = make;
        this.model = model;
    }

    // Method to Display Details
    public void DisplayDetails()
    {
        Console.WriteLine($"Car Make: {Make}, Model: {model}");
    }
}

// Accessing fields and methods
Car myCar = new Car("Audi", "A6");
myCar.DisplayDetails();  // Output: Car Make: Audi, Model: A6
    

5. Real-World Example: Bank Account Class

Let's consider a real-world scenario where you want to model a bank account with basic operations like depositing and withdrawing money.


class BankAccount
{
    // Fields
    private double balance;

    // Constructor
    public BankAccount(double initialBalance)
    {
        balance = initialBalance;
    }

    // Method to Deposit Money
    public void Deposit(double amount)
    {
        balance += amount;
        Console.WriteLine($"Deposited: {amount}. Current balance: {balance}");
    }

    // Method to Withdraw Money
    public void Withdraw(double amount)
    {
        if (amount > balance)
        {
            Console.WriteLine("Insufficient funds.");
        }
        else
        {
            balance -= amount;
            Console.WriteLine($"Withdrew: {amount}. Current balance: {balance}");
        }
    }

    // Method to Display Current Balance
    public void DisplayBalance()
    {
        Console.WriteLine($"Current balance: {balance}");
    }
}

// Using BankAccount class
BankAccount account = new BankAccount(1000);
account.Deposit(500);  // Output: Deposited: 500. Current balance: 1500
account.Withdraw(200); // Output: Withdrew: 200. Current balance: 1300
account.DisplayBalance();  // Output: Current balance: 1300
    

6. Conclusion

Classes and objects form the core of object-oriented programming in C#. Understanding how to define classes, create objects, and apply the various features like constructors, methods, access modifiers, and destructors will help you design scalable and efficient applications.

Quiz: C# Classes and Objects