Skip to main content

C# Classes and Objects

Introduction

Classes and objects are the core concepts of Object-Oriented Programming (OOP) in C#. If you're transitioning from procedural programming or just starting with C#, understanding these concepts is crucial for your development journey.

A class is essentially a blueprint or template that defines the characteristics and behaviors of a particular type of object. An object is an instance of a class—a concrete entity created from that blueprint, which takes up memory and can be manipulated in your program.

In this tutorial, we'll explore how classes and objects work in C#, and how you can leverage them to write cleaner, more organized, and reusable code.

Understanding Classes in C#

Class Definition

In C#, a class is defined using the class keyword followed by the class name and a pair of curly braces that contain the class members.

csharp
public class Car
{
// Class members go here
}

By convention, class names in C# use PascalCase (each word capitalized with no spaces).

Class Members

A class can contain the following members:

  1. Fields - Variables that store data
  2. Properties - Special methods that provide access to fields
  3. Methods - Functions that perform actions
  4. Constructors - Special methods called when creating objects
  5. Events - Notifications that can be triggered and handled
  6. Nested types - Classes or other types defined within the class

Let's create a more complete Car class:

csharp
public class Car
{
// Fields
private string _make;
private string _model;
private int _year;
private double _currentSpeed;

// Constructor
public Car(string make, string model, int year)
{
_make = make;
_model = model;
_year = year;
_currentSpeed = 0;
}

// Properties
public string Make
{
get { return _make; }
}

public string Model
{
get { return _model; }
}

public int Year
{
get { return _year; }
}

public double CurrentSpeed
{
get { return _currentSpeed; }
}

// Methods
public void Accelerate(double amount)
{
_currentSpeed += amount;
Console.WriteLine($"The car is now traveling at {_currentSpeed} mph.");
}

public void Brake(double amount)
{
_currentSpeed = Math.Max(0, _currentSpeed - amount);
Console.WriteLine($"The car is now traveling at {_currentSpeed} mph.");
}

public string GetCarInfo()
{
return $"{_year} {_make} {_model}";
}
}

Creating and Using Objects

Object Instantiation

To create an object from a class, you use the new keyword followed by a call to the class constructor:

csharp
Car myCar = new Car("Toyota", "Corolla", 2022);

This creates a new Car object in memory and assigns it to the variable myCar.

Accessing Object Members

Once you have an object, you can access its members using the dot (.) notation:

csharp
// Accessing properties
string carMake = myCar.Make; // "Toyota"
int carYear = myCar.Year; // 2022

// Calling methods
myCar.Accelerate(30);
string info = myCar.GetCarInfo(); // "2022 Toyota Corolla"

Complete Example

Let's see a complete example of creating and using the Car class:

csharp
using System;

class Program
{
static void Main(string[] args)
{
// Create a new Car object
Car myCar = new Car("Honda", "Civic", 2021);

// Display car information
Console.WriteLine($"My car is a {myCar.GetCarInfo()}");

// Accelerate the car
myCar.Accelerate(25);

// Accelerate more
myCar.Accelerate(15);

// Apply brakes
myCar.Brake(10);

Console.ReadLine();
}
}

public class Car
{
// Class implementation (same as above)
// ...
}

Output:

My car is a 2021 Honda Civic
The car is now traveling at 25 mph.
The car is now traveling at 40 mph.
The car is now traveling at 30 mph.

Advanced Class Features

Auto-Implemented Properties

C# provides a shorthand syntax for creating properties when no additional logic is needed:

csharp
public class Person
{
// Auto-implemented properties
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

// Read-only property (can only be set in constructor or initialization)
public string FullName { get; }

public Person(string firstName, string lastName, int age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
FullName = $"{FirstName} {LastName}";
}
}

Static Members

Static members belong to the class itself rather than to any specific object:

csharp
public class MathHelper
{
// Static field
public static double PI = 3.14159;

// Static method
public static double CalculateCircleArea(double radius)
{
return PI * radius * radius;
}
}

// Usage (no object creation needed):
double area = MathHelper.CalculateCircleArea(5);
Console.WriteLine($"The area is {area}");

Object Initialization Syntax

C# provides a concise way to initialize objects:

csharp
// Using object initializer syntax
Person person = new Person
{
FirstName = "John",
LastName = "Doe",
Age = 30
};

Practical Example: Building a Student Management System

Let's create a more practical example of a simple student management system:

csharp
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
// Create a course
Course programmingCourse = new Course("CS101", "Introduction to Programming");

// Add students to the course
programmingCourse.AddStudent(new Student("Alice", "Smith", 12345));
programmingCourse.AddStudent(new Student("Bob", "Johnson", 67890));
programmingCourse.AddStudent(new Student("Charlie", "Williams", 13579));

// Display course information
Console.WriteLine(programmingCourse.GetCourseInfo());

// Display enrolled students
programmingCourse.ListEnrolledStudents();
}
}

public class Student
{
public string FirstName { get; }
public string LastName { get; }
public int StudentID { get; }

public Student(string firstName, string lastName, int studentID)
{
FirstName = firstName;
LastName = lastName;
StudentID = studentID;
}

public string GetFullName()
{
return $"{FirstName} {LastName}";
}
}

public class Course
{
public string CourseCode { get; }
public string CourseName { get; }
private List<Student> EnrolledStudents { get; }

public Course(string courseCode, string courseName)
{
CourseCode = courseCode;
CourseName = courseName;
EnrolledStudents = new List<Student>();
}

public void AddStudent(Student student)
{
EnrolledStudents.Add(student);
Console.WriteLine($"{student.GetFullName()} has been enrolled in {CourseName}.");
}

public string GetCourseInfo()
{
return $"Course: {CourseCode} - {CourseName}\nEnrolled Students: {EnrolledStudents.Count}";
}

public void ListEnrolledStudents()
{
Console.WriteLine("\nEnrolled Students:");
foreach (Student student in EnrolledStudents)
{
Console.WriteLine($"ID: {student.StudentID}, Name: {student.GetFullName()}");
}
}
}

Output:

Alice Smith has been enrolled in Introduction to Programming.
Bob Johnson has been enrolled in Introduction to Programming.
Charlie Williams has been enrolled in Introduction to Programming.
Course: CS101 - Introduction to Programming
Enrolled Students: 3

Enrolled Students:
ID: 12345, Name: Alice Smith
ID: 67890, Name: Bob Johnson
ID: 13579, Name: Charlie Williams

This example demonstrates several key OOP concepts:

  • Creating multiple classes that work together
  • Using a collection to store objects
  • Encapsulation (protecting data with private fields and exposing functionality through methods)
  • Object relationships (a Course "has-a" list of Students)

Best Practices for Classes and Objects

  1. Follow the Single Responsibility Principle: Each class should have only one reason to change.
  2. Use Proper Encapsulation: Make fields private and expose them through properties when necessary.
  3. Initialize Objects Fully: Ensure that objects are in a valid state after construction.
  4. Follow Naming Conventions: Use PascalCase for class names and properties, camelCase for method parameters and local variables.
  5. Document Your Classes: Use comments to explain what classes do and how to use them.
  6. Keep Classes Focused: Avoid creating "god classes" that do too much.

Summary

Classes and objects are fundamental concepts in C# and object-oriented programming. Classes serve as blueprints that define the structure and behavior of objects, while objects are instances of these classes that occupy memory and can be manipulated in your code.

In this tutorial, you've learned:

  • How to define classes with fields, properties, methods, and constructors
  • How to create and use objects
  • Advanced features like auto-implemented properties and static members
  • A practical application of classes in a student management system

Understanding these concepts will help you build more organized, reusable, and maintainable C# applications as you progress in your programming journey.

Exercises

To strengthen your understanding of classes and objects, try these exercises:

  1. Create a BankAccount class with properties for account number, owner name, and balance. Add methods for deposit and withdrawal that update the balance.

  2. Extend the Car class to include additional properties like FuelLevel and methods like Refuel().

  3. Create a Library class that manages a collection of Book objects. Include methods to add books, remove books, and search for books by title or author.

  4. Design a Rectangle class with properties for width and height, and methods to calculate area and perimeter.

  5. Implement a Person class and a Family class that contains a collection of Person objects. Add methods to add family members and find the oldest person in the family.

Additional Resources

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)