Skip to main content

C# Classes and Objects

C# is a powerful programming language that thrives on the principles of Object-Oriented Programming (OOP). 

At the core of OOP are two fundamental concepts: classes and objects. 

If you've ever wondered how these concepts work or how they can simplify your code, you've come to the right place. 

Let’s explore C# classes and objects in detail.

What Are Classes?

Think of a class as a blueprint for creating objects. 

Just like an architect creates a blueprint for a house, a class defines the structure and behavior of objects. 

It contains properties (attributes) and methods (functions) that describe what an object can do.

For instance, consider a Car class. This class would have properties like Color, Make, and Model. It could also include methods like Drive and Stop. Here's a simple example in C#:

public class Car
{
    public string Color { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }

    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }

    public void Stop()
    {
        Console.WriteLine("The car has stopped.");
    }
}

In this code, the Car class defines three properties and two methods. Now, let’s make a car object based on this blueprint.

Creating Objects

To create an object, you instantiate a class. 

Think of it as building a house from the blueprint. Here’s how you can create a Car object in C#:

Car myCar = new Car();
myCar.Color = "Red";
myCar.Make = "Toyota";
myCar.Model = "Corolla";

myCar.Drive();  // Outputs: The car is driving.

In this example, myCar is an object of the Car class. You can set its properties and call its methods. 

This ability to create multiple objects from the same class makes your code versatile and clean.

Properties and Methods Explained

Properties

Properties in a class help define the characteristics of an object. 

They can be of different types, such as string, int, or even other classes. Using properties efficiently can enhance the functionality of your object.

Continuing with our Car example, you might want to add a property to track its speed. Here’s how:

public int Speed { get; set; }

Now, you can add logic to manage the speed:

public void Accelerate(int increase)
{
    Speed += increase;
    Console.WriteLine("The car accelerated to " + Speed + " mph.");
}

public void Decelerate(int decrease)
{
    Speed -= decrease;
    Console.WriteLine("The car decelerated to " + Speed + " mph.");
}

Methods

Methods define the actions that can be performed on an object. 

They can manipulate the properties of the class, perform calculations, or return values. 

In our Car class, methods like Drive, Stop, Accelerate, and Decelerate give the car functionality.

Here’s how to use these new methods:

myCar.Accelerate(20); // Outputs: The car accelerated to 20 mph.
myCar.Decelerate(10); // Outputs: The car decelerated to 10 mph.

Encapsulation

Encapsulation is a critical principle of OOP. It protects the internal state of an object by restricting direct access to its properties. 

Instead, it exposes methods for interacting with the data. 

This ensures the integrity of your data and hides implementation details.

You can implement encapsulation by using access modifiers like private and public. Here’s an example:

public class Car
{
    private int speed;

    public void Accelerate(int increase)
    {
        speed += increase;
        Console.WriteLine("The car accelerated to " + speed + " mph.");
    }

    public void Decelerate(int decrease)
    {
        speed -= decrease;
        Console.WriteLine("The car decelerated to " + speed + " mph.");
    }
}

In this code, the speed property is private. 

The public methods Accelerate and Decelerate manage the speed variable, maintaining control over how it’s accessed.

Inheritance: A Step Further

Another essential feature of classes in C# is inheritance. 

This allows you to create a new class based on an existing class, inheriting its properties and methods. Imagine you want to create a SportsCar class. 

It can inherit from the Car class and add more specific features:

public class SportsCar : Car
{
    public bool HasTurbo { get; set; }

    public void ActivateTurbo()
    {
        if (HasTurbo)
        {
            Console.WriteLine("Turbo activated!");
        }
    }
}

Now, your SportsCar class has all the properties and methods of Car but also includes functionality specific to sports cars. 

You can create a SportsCar object and use it just like a Car.

SportsCar mySportsCar = new SportsCar();
mySportsCar.Color = "Blue";
mySportsCar.Make = "Ferrari";
mySportsCar.Model = "488";

mySportsCar.HasTurbo = true;
mySportsCar.ActivateTurbo(); // Outputs: Turbo activated!

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...