c sharp

How to Understand and Use Nested Classes in C#

One of the most comprehensive and extensive programming paradigms in modern age is OOP. Some of the most commonly used and applied components in OOP include: encapsulation, polymorphism, and inheritance.

However, one of the most underrated subset of all these is the nested classes. It is a simple technique but can produce a powerful and very maintainable code.

What Are Nested Classes?

Nested classes are basically classes that are defined within another class. They are incredibly useful when you need to encapsulate the data in a modular format.

Nested classes come into play when the inner class is relevant in the context of an outer class. For example, a “Book” class can be a nested class of the library class.

The Basics

Let us start with the basics and learn how to declare and use the nested classes. As the name suggests, we define a nested class within the body of the outer class.

The following example shows the syntax of defining a nested class:

public class Parent
{
    public class ChildClass
    {
        public void Display()
        {
            Console.WriteLine("Hello from the nested class!");
        }
    }
}

In this example, the ChildClass is nested inside the “Parent” class. We also define a method which acts as a member of the nested class.

To create an instance of a nested class, we can use the syntax as follows:

Parent.ChildClass nestedObject = new Parent.ChildClass();

Once we create the nested object, we can access the member method as follows:

nestedObject.Display();

Access Modifiers

Like any class in C#, nested classes do support the access modifiers which determine their accessibility throughout the application.

Apart from private, we can also set the other access modifiers to a nested class such as public, protected, and internal.

The following are the supported access modifiers and what each does to the nested class:

  • Public – The nested class is accessible from any part of the code, including outside the containing assembly.
  • Private – The nested class is only accessible within the containing outer class.
  • Protected – In a protected context, the inner class becomes accessible within the outer class and its derived classes.
  • Internal – In this case, the nested class is accessible within the same assembly but not from another assembly.
  • Protected Internal – This is accessible within its containing assembly and by derived classes of the outer class, regardless of assembly.
  • Private Protected (C# 7.2+) – This is accessible within the containing class and by derived classes, but only if they are in the same assembly.

Practical Example:

The following shows a basic representational usage of a nested class in C#. This in no way or form represent the real-world usage:

using System;
using System.Data.SQLite;
public class DatabaseManager
{
    private string _connectionString;
    public DatabaseManager(string connectionString)
    {
        _connectionString = connectionString;
    }
    public class SqlConnection
    {
        private SQLiteConnection _connection;

        public SqlConnection(string connectionString)
        {
            _connection = new SQLiteConnection(connectionString);
        }
        public void OpenConnection()
        {
            _connection.Open();
            Console.WriteLine("Database connection opened.");
        }

        public void CloseConnection()
        {
            _connection.Close();
            Console.WriteLine("Database connection closed.");
        }
    }


    public void ExecuteDatabaseOperation(Action<SqlConnection> operation)
    {
        var connection = new SqlConnection(_connectionString);
        connection.OpenConnection();

        try
        {
            operation(connection);
        }
        finally
        {
            connection.CloseConnection();
        }
    }
}

In this case, the “SqlConnection” class is nested inside the “DatabaseManager” class. We can use the code as follows:

public class Program
    {
        public static void Main()
        {
            string connectionString = "Data Source=sample.db;Version=3;"; // replace with your actual connection string
            var dbManager = new DatabaseManager(connectionString);
            dbManager.ExecuteDatabaseOperation(connection =>
        {
            Console.WriteLine("Performing database operations...");
        });
    }
}

This utilizes the methods that are provided by the nested class to perform the tasks such as opening the connections, closing the connections, executing the queries, etc.

Conclusion

In this tutorial, we learned how to create and use the nested classes in a C# app to create a modular code.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list