C# Classes & Objects

Learn C# Classes & Objects with practical examples, explanations, best practices, and real-world coding techniques.

Classes and objects are fundamental concepts in C# and object-oriented programming (OOP). When building software, developers often need to represent entities such as students, customers, products, employees, and orders. Classes provide a structured way to define these entities, while objects represent individual instances created from those definitions.

A class describes the data an entity can hold and the operations it can perform. An object combines that data and behavior into an instance that a program can use. Understanding this relationship helps you organize code into reusable components rather than placing all application logic in one large method.

1. What Is a Class in C#?

A class is a user-defined reference type that describes the structure and behavior of a particular concept. It can contain fields, properties, constructors, methods, events, and other members. A class declaration defines what its instances can contain and do.

For example, a car may have a brand and model, and it may provide operations such as starting its engine. These details can be represented by a C# class.

using System;

public class Car
{
    public string Brand = string.Empty;
    public string Model = string.Empty;
    public int Year;

    public void DisplayDetails()
    {
        Console.WriteLine($"{Year} {Brand} {Model}");
    }
}

In this example, Car is the class name. Brand, Model, and Year are fields that store data. The DisplayDetails() method defines behavior by displaying the car's information.

The class declaration describes a type, but it does not automatically create a specific car object. An instance must be created before instance members can be accessed.

2. Creating Objects with the new Keyword

An object is an instance of a class. In typical C# code, the new keyword creates an instance and invokes an appropriate constructor. You can then access public instance members using the dot operator.

Car myCar = new Car();

myCar.Brand = "Toyota";
myCar.Model = "Corolla";
myCar.Year = 2024;

myCar.DisplayDetails();

Output:

2024 Toyota Corolla

The variable myCar holds a reference to the created object. The dot operator allows the program to read or modify accessible members and call methods on that instance.

You can create multiple instances from the same class. Each instance normally maintains its own instance fields and properties, so changing one object's data does not automatically change another object's data.

Car car1 = new Car
{
    Brand = "BMW",
    Model = "3 Series",
    Year = 2023
};

Car car2 = new Car
{
    Brand = "Audi",
    Model = "A4",
    Year = 2025
};

car1.DisplayDetails();
car2.DisplayDetails();

3. Fields and Properties

Fields and properties both represent data associated with an object, but they serve different purposes. A field is a variable declared inside a type. A property provides accessors that define how a value can be read or assigned.

Although public fields are useful for simple demonstrations, application code commonly uses properties to expose object data in a controlled way.

public class Student
{
    public string Name { get; set; } = string.Empty;

    public int Age { get; set; }

    public string Course { get; private set; } = string.Empty;

    public void Enroll(string course)
    {
        Course = course;
    }
}

The { get; set; } syntax declares an auto-implemented property. The compiler provides the underlying storage. A property with private set can be read publicly but assigned only from within the declaring type.

Properties can also validate values through custom accessors or use a private backing field. This allows a class to protect its internal state and enforce rules instead of permitting arbitrary modifications.

public class Product
{
    private decimal price;

    public decimal Price
    {
        get => price;
        set
        {
            if (value < 0)
            {
                throw new ArgumentOutOfRangeException(
                    nameof(value),
                    "Price cannot be negative.");
            }

            price = value;
        }
    }
}

Here, the Price property rejects negative values. This kind of validation helps preserve valid object state and makes business rules easier to maintain.

4. Constructors and Object Initialization

A constructor is a special member that runs when an instance is created. Constructors commonly initialize fields and properties so that objects begin in a meaningful state.

public class Student
{
    public string Name { get; }
    public int Age { get; }

    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void Introduce()
    {
        Console.WriteLine($"I am {Name} and I am {Age} years old.");
    }
}

The constructor accepts a name and age, then assigns them to read-only properties. Those properties can be read by other code but cannot be reassigned through ordinary property assignment after construction.

Student student = new Student("Asha", 21);

student.Introduce();

A class can define multiple constructors with different parameter lists. This is called constructor overloading. If you declare no instance constructor, C# generally provides a public parameterless constructor for a class, subject to the applicable language rules. Once you declare an instance constructor, that automatically provided constructor is no longer supplied.

Object initializers offer another convenient way to assign accessible properties during creation:

public class Course
{
    public string Title { get; set; } = string.Empty;
    public int DurationInHours { get; set; }
}

Course course = new Course
{
    Title = "C# Fundamentals",
    DurationInHours = 12
};

5. Instance Members and Static Members

Instance members belong to individual objects. Static members belong to the type itself rather than to a particular instance. Use instance members for data that differs between objects and static members for shared functionality or type-level state.

public class User
{
    public string Name { get; set; } = string.Empty;

    public static int TotalUsers { get; private set; }

    public User(string name)
    {
        Name = name;
        TotalUsers++;
    }
}

You can access the static property using the class name:

User first = new User("Asha");
User second = new User("Ravi");

Console.WriteLine(first.Name);
Console.WriteLine(second.Name);
Console.WriteLine(User.TotalUsers);

Each user has a separate Name property, while TotalUsers is shared across instances of the type. Static state should be designed carefully in applications with concurrent operations, especially when shared values are modified by multiple threads.

6. Methods Define Object Behavior

Methods represent operations a class can perform. They may accept parameters, return values, modify an object's state, or coordinate other operations. Keeping behavior close to the data it manages can make classes easier to understand and maintain.

public class BankAccount
{
    public string AccountHolder { get; }
    public decimal Balance { get; private set; }

    public BankAccount(string accountHolder, decimal initialBalance)
    {
        if (initialBalance < 0)
        {
            throw new ArgumentOutOfRangeException(
                nameof(initialBalance));
        }

        AccountHolder = accountHolder;
        Balance = initialBalance;
    }

    public void Deposit(decimal amount)
    {
        if (amount <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(amount));
        }

        Balance += amount;
    }
}

The BankAccount class protects its balance by using a private setter. Other code cannot directly assign an arbitrary balance through the public property, and the Deposit() method validates the amount before updating it.

This example illustrates encapsulation: a class controls how its internal state is accessed and modified. In production financial systems, additional rules, concurrency controls, persistence, and transaction handling may also be required.

7. Understanding Reference Types and Object References

Classes are reference types. A variable of a class type holds a reference to an object rather than containing the object's instance data directly. Assigning one class variable to another copies the reference, so both variables can refer to the same object.

public class Person
{
    public string Name { get; set; } = string.Empty;
}

Person person1 = new Person { Name = "Asha" };
Person person2 = person1;

person2.Name = "Ravi";

Console.WriteLine(person1.Name); // Ravi
Console.WriteLine(person2.Name); // Ravi

Both variables reference the same instance. Changing the object's Name property through either reference is visible through the other reference.

If you create a separate object, the instances are independent unless they share other referenced data. Understanding this behavior is important when passing objects to methods, storing objects in collections, and designing APIs.

8. Classes, Encapsulation, and Object-Oriented Design

Classes are a foundation of object-oriented programming, but a good class should do more than hold a collection of unrelated fields. It should represent a clear concept and provide operations that make sense for that concept.

  • Encapsulation: Keep implementation details private and expose controlled operations through public members.
  • Abstraction: Provide a clear interface without requiring callers to understand every internal detail.
  • Inheritance: Allow a derived class to reuse or extend behavior from a base class when there is a genuine subtype relationship.
  • Polymorphism: Enable code to work with a common base type or interface while different implementations provide their own behavior.

For example, a student management application might contain separate Student, Course, and Enrollment classes. Each class represents a distinct concept and owns the properties and behavior relevant to it.

Avoid making one class responsible for every part of an application. Clear responsibilities improve testability, reduce coupling, and make it easier to change one part of the system without affecting unrelated functionality.

9. Common Mistakes When Working with Classes

  • Creating public fields for all data when controlled properties would better protect object state.
  • Allowing objects to exist in invalid states because required values are not validated.
  • Confusing a class declaration with an object instance.
  • Assuming that assigning one object variable to another creates an independent copy.
  • Using static mutable state for information that should belong to individual objects.
  • Putting unrelated responsibilities into a single large class.
  • Using inheritance only to reuse code when composition would represent the relationship more clearly.

10. Practical Example: A Student Management Model

The following example combines properties, a constructor, validation, and a method to model a student. It demonstrates how a class can keep related data and behavior together while maintaining basic rules about its state.

using System;

public class Student
{
    public string Name { get; }
    public int Age { get; }
    public string Course { get; private set; }

    public Student(string name, int age, string course)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException(
                "Name is required.", nameof(name));
        }

        if (age < 1)
        {
            throw new ArgumentOutOfRangeException(nameof(age));
        }

        if (string.IsNullOrWhiteSpace(course))
        {
            throw new ArgumentException(
                "Course is required.", nameof(course));
        }

        Name = name;
        Age = age;
        Course = course;
    }

    public void ChangeCourse(string newCourse)
    {
        if (string.IsNullOrWhiteSpace(newCourse))
        {
            throw new ArgumentException(
                "Course is required.", nameof(newCourse));
        }

        Course = newCourse;
    }

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

Student student = new Student("Asha", 21, "C#");
student.DisplayDetails();

student.ChangeCourse("ASP.NET Core");
student.DisplayDetails();

The constructor validates required values, while ChangeCourse() controls how the course is updated. The class exposes only the members needed by callers and keeps the update rules inside the object.

This design can be expanded with identifiers, enrollment dates, or methods that represent additional student operations. As the application grows, related classes can work together to represent more complex business processes.

Best Practices for Classes and Objects in C#

  • Give each class a clear responsibility and a descriptive name.
  • Prefer properties over public fields for most application models.
  • Use constructors to establish required initial state.
  • Validate input at appropriate boundaries and protect important invariants.
  • Use access modifiers such as private, protected, and public intentionally.
  • Choose instance members for object-specific information and static members only for genuinely type-level behavior or state.
  • Understand reference assignment before sharing mutable objects across methods or components.
  • Favor composition over inheritance when a class simply needs to use another object.

Classes and objects provide the structure needed to build maintainable C# applications. By combining data with meaningful behavior, protecting internal state, and designing clear responsibilities, you create a foundation for more advanced topics such as inheritance, interfaces, and the broader principles of object-oriented programming.

Code Examples

Create a Class and Instantiate Objects

csharp
using System;

public class Student
{
    public string Name { get; }
    public int Age { get; }

    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }

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

Student student1 = new Student("Asha", 21);
Student student2 = new Student("Ravi", 23);

student1.Introduce();
student2.Introduce();
    

Encapsulation with Properties and Methods

csharp
using System;

public class BankAccount
{
    public string AccountHolder { get; }
    public decimal Balance { get; private set; }

    public BankAccount(string accountHolder, decimal initialBalance)
    {
        if (initialBalance < 0)
        {
            throw new ArgumentOutOfRangeException(
                nameof(initialBalance));
        }

        AccountHolder = accountHolder;
        Balance = initialBalance;
    }

    public void Deposit(decimal amount)
    {
        if (amount <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(amount));
        }

        Balance += amount;
    }
}

BankAccount account = new BankAccount("Asha", 500m);
account.Deposit(150m);

Console.WriteLine($"{account.AccountHolder}: {account.Balance:C}");
    

Pro Tip

Design each class around a clear responsibility. Prefer properties with controlled access over public fields, initialize required state through constructors, and keep business rules inside the class that owns the data.

More C# lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.