← Back to list

C# Classes and Objects

The Building Blocks You Use Every Day

Jathurshan Santhirasekaram | C#.NET | JS | SQL ✨ in Write A Catalyst · 2026-06-03 05:28 · 77 claps · 4.4 min read paywalled
#write-a-catalyst #class-and-object #csharp #programming #coding
Open on Medium ↗
Wiki topics: 💻 · Programming 🧪 · Chemistry

C# Classes and Objects

The Building Blocks You Use Every Day

Everything you write in C# lives inside a class. Here’s how they actually work.

AI Generated

AI Generated

If you’ve written even a few lines of C#, you’ve used a class. But there’s a difference between using classes and understanding them. Once the mental model clicks, everything else — inheritance, interfaces, design patterns — starts to make sense.

Let’s build that model from scratch.

What Is a Class?

A class is a blueprint. It describes what something is and what it can do.

Think of a class like an architect’s floor plan. The plan itself isn’t a house — it’s the description of a house. You use it to build as many actual houses as you want.

public class Car
{
    public string Brand;
    public string Color;
    public int Year;
    public void StartEngine()
    {
        Console.WriteLine($"{Brand} engine started!");
    }
}

That’s a class. It defines that a Car has a brand, a color, a year, and can start its engine. No actual car exists yet — just the blueprint.

What Is an Object?

An object is a real instance created from a class. Using the new keyword, you bring the blueprint to life.

Car myCar = new Car();
myCar.Brand = "Toyota";
myCar.Color = "Red";
myCar.Year  = 2023;
myCar.StartEngine(); // Output: Toyota engine started!

myCar is an object — a concrete, living instance of the Car class. You can create as many as you want:

Car anotherCar = new Car();
anotherCar.Brand = "BMW";

Each object has its own data. Changing anotherCar.Brand has zero effect on myCar.

Fields, Properties, and Methods

Classes are made of three core ingredients.

Fields

Raw variables that store data. Usually kept private.

private string _brand;

Properties

The polished, controlled way to expose data. Properties let you add logic — validation, formatting — around a field.

public string Brand
{
    get { return _brand; }
    set
    {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Brand cannot be empty.");
        _brand = value;
    }
}

Or the short form when you don’t need custom logic:

public string Color { get; set; }

Methods

Actions the object can perform.

public void StartEngine()
{
    Console.WriteLine($"{Brand} engine started!");
}
public string GetInfo()
{
    return $"{Year} {Brand} in {Color}";
}

Constructors: Setting Up an Object at Birth

A constructor is a special method that runs the moment an object is created. Use it to set required values upfront instead of assigning them one by one.

public class Car
{
    public string Brand { get; set; }
    public string Color { get; set; }
    public int Year { get; set; }
    // Constructor
    public Car(string brand, string color, int year)
    {
        Brand = brand;
        Color = color;
        Year  = year;
    }
    public void StartEngine()
    {
        Console.WriteLine($"{Brand} engine started!");
    }
}

Now creating a car is clean and explicit:

Car myCar = new Car("Toyota", "Red", 2023);
myCar.StartEngine(); // Toyota engine started!

No half-built objects floating around. The constructor enforces that every car starts life fully formed.

Access Modifiers: Who Can See What

C# gives you fine-grained control over visibility.

Modifier Accessible From public Anywhere private Inside the same class only protected Inside the class and its subclasses internal Inside the same project/assembly

The golden rule: make things as private as possible. Only expose what others genuinely need.

public class BankAccount
{
    private decimal _balance; // hidden from the outside world
    public void Deposit(decimal amount)
    {
        if (amount > 0)
            _balance += amount;
    }
    public decimal GetBalance() => _balance;
}

Nobody can reach in and change _balance directly. They have to go through Deposit(), where you control what happens.

Static vs Instance Members

By default, every object gets its own copy of every field and method. These are called instance members.

But sometimes you want something shared across all objects — a counter, a config value, a utility method. That’s what static is for.

public class Car
{
    public static int TotalCarsCreated = 0; // shared by all
    public string Brand { get; set; }
    public Car(string brand)
    {
        Brand = brand;
        TotalCarsCreated++; // increments for every new car
    }
}
Car c1 = new Car("Toyota");
Car c2 = new Car("BMW");
Car c3 = new Car("Ford");
Console.WriteLine(Car.TotalCarsCreated); // 3

Notice: you access static members via the class name (Car.TotalCarsCreated), not via an object instance.

Inheritance: Building on What Exists

One of C#’s most powerful features. A class can inherit from another, gaining all its properties and methods — and adding its own on top.

public class Vehicle
{
    public string Brand { get; set; }
    public int Year { get; set; }
    public void StartEngine()
    {
        Console.WriteLine($"{Brand} engine started!");
    }
}
public class ElectricCar : Vehicle // inherits from Vehicle
{
    public int BatteryRange { get; set; }
    public void ChargeBattery()
    {
        Console.WriteLine($"Charging {Brand}... Range: {BatteryRange}km");
    }
}
ElectricCar tesla = new ElectricCar();
tesla.Brand       = "Tesla";
tesla.Year        = 2024;
tesla.BatteryRange = 500;
tesla.StartEngine();   // inherited from Vehicle
tesla.ChargeBattery(); // ElectricCar's own method

ElectricCar didn't have to rewrite StartEngine(). It got it for free from Vehicle. That's inheritance: reuse without repetition.

Putting It All Together

Here’s a complete, realistic example that uses everything above:

public class BankAccount
{
    private decimal _balance;
    private static int _totalAccounts = 0;
    public string Owner { get; private set; }
    public int AccountNumber { get; private set; }
    public BankAccount(string owner, decimal initialDeposit)
    {
        Owner = owner;
        _balance = initialDeposit;
        _totalAccounts++;
        AccountNumber = _totalAccounts;
    }
    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentException("Amount must be positive.");
        _balance += amount;
        Console.WriteLine($"Deposited {amount:C}. New balance: {_balance:C}");
    }
    public void Withdraw(decimal amount)
    {
        if (amount > _balance) throw new InvalidOperationException("Insufficient funds.");
        _balance -= amount;
        Console.WriteLine($"Withdrew {amount:C}. New balance: {_balance:C}");
    }
    public decimal GetBalance() => _balance;
    public static int GetTotalAccounts() => _totalAccounts;
}
var account1 = new BankAccount("Alice", 1000m);
var account2 = new BankAccount("Bob", 500m);
account1.Deposit(200m);   // Deposited $200.00. New balance: $1,200.00
account1.Withdraw(150m);  // Withdrew $150.00. New balance: $1,050.00
Console.WriteLine(BankAccount.GetTotalAccounts()); // 2

Clean. Safe. Predictable. Everything a well-designed class should be.

The Mental Model to Keep

Concept What It Is Class The blueprint Object A real instance built from the blueprint Field Raw data storage Property Controlled access to data Method An action the object performs Constructor Sets up the object at creation time Static Belongs to the class, not any one object Inheritance A class that builds on another class

Classes and objects are where C# begins. Once you’re comfortable with them, you’re ready to explore interfaces, abstract classes, generics, and design patterns — all of which are just these same ideas, taken further.

Master the blueprint. Everything else follows.

Found this useful? Follow for more C# fundamentals explained clearly. Next up: interfaces and why they matter more than inheritance.


메타데이터
post_id
a6f45f950db6
slug
c-classes-and-objects-a6f45f950db6
url
https://medium.com/write-a-catalyst/c-classes-and-objects-a6f45f950db6
canonical_url
https://medium.com/write-a-catalyst/c-classes-and-objects-a6f45f950db6
author_url
https://medium.com/@code_santa
status
ok
fetched_at
2026-08-24 05:51:34