C# Classes and Objects

Welcome to The Coding College! In this tutorial, we’ll cover classes and objects in C#, the building blocks of Object-Oriented Programming (OOP). Understanding these concepts is fundamental to writing efficient, reusable, and scalable code in C#.

What is a Class in C#?

A class in C# is a blueprint for creating objects. It defines the properties (data) and methods (behavior) that the objects created from the class will have.

Syntax:

public class ClassName
{
    // Fields (variables)
    // Properties
    // Methods
}

What is an Object in C#?

An object is an instance of a class. When you create an object, you allocate memory and initialize the fields and properties defined in the class.

Syntax:

ClassName objectName = new ClassName();

How to Create a Class and Object

Let’s create a simple class and an object in C#.

Example:

// Define a class
public class Car
{
    public string Brand; // Field
    public string Model; // Field
    public int Year;     // Field

    public void DisplayInfo() // Method
    {
        Console.WriteLine($"Brand: {Brand}, Model: {Model}, Year: {Year}");
    }
}

// Create an object
public class Program
{
    public static void Main()
    {
        Car car = new Car(); // Object instantiation
        car.Brand = "Tesla";
        car.Model = "Model S";
        car.Year = 2023;

        car.DisplayInfo(); // Output: Brand: Tesla, Model: Model S, Year: 2023
    }
}

Fields, Properties, and Methods

  1. Fields: Variables declared inside a class that store data.
  2. Properties: Encapsulated access to the class’s fields, allowing controlled data manipulation.
  3. Methods: Actions or functions that define the behavior of an object.

Fields Example

public class Student
{
    public string Name;   // Field
    public int Age;       // Field
}

Properties Example

public class Student
{
    private string name;  // Private field

    public string Name    // Property
    {
        get { return name; }
        set { name = value; }
    }
}

Methods Example

public class Student
{
    public string Name;

    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name}.");
    }
}

Constructor in C#

A constructor is a special method used to initialize objects. It is called automatically when an object is created.

Syntax:

public ClassName()
{
    // Initialization code
}

Example:

public class Person
{
    public string Name;
    public int Age;

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

    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

public class Program
{
    public static void Main()
    {
        Person person = new Person("John", 25);
        person.DisplayInfo(); // Output: Name: John, Age: 25
    }
}

Real-World Example: C# Classes and Objects

Imagine a class that models a bank account.

public class BankAccount
{
    public string AccountHolder;
    public double Balance;

    public void Deposit(double amount)
    {
        Balance += amount;
        Console.WriteLine($"Deposited: {amount}. New Balance: {Balance}");
    }

    public void Withdraw(double amount)
    {
        if (amount <= Balance)
        {
            Balance -= amount;
            Console.WriteLine($"Withdrawn: {amount}. New Balance: {Balance}");
        }
        else
        {
            Console.WriteLine("Insufficient balance.");
        }
    }
}

public class Program
{
    public static void Main()
    {
        BankAccount account = new BankAccount();
        account.AccountHolder = "Alice";
        account.Balance = 1000;

        account.Deposit(500);  // Output: Deposited: 500. New Balance: 1500
        account.Withdraw(200); // Output: Withdrawn: 200. New Balance: 1300
    }
}

Advantages of Using Classes and Objects in C#

  1. Modularity: Classes organize your code into reusable modules.
  2. Encapsulation: Protects the data from unintended access or modification.
  3. Abstraction: Simplifies complex systems by hiding unnecessary details.
  4. Reusability: Use the same class to create multiple objects.

Conclusion

Classes and objects are the cornerstone of C# programming. Mastering these concepts is essential for building robust, modular, and scalable applications. By combining fields, properties, methods, and constructors, you can create powerful, reusable code structures.

For more tutorials and guides, visit The Coding College.

Leave a Comment