Unlocking the Power of Nested Classes in C#
Understanding Nested Classes
In C#, you can define a class within another class, a concept known as a nested class. This powerful feature allows for better organization and structure in your code.
Creating a Nested Class
Consider a scenario where we have a Car
class with an Engine
class nested inside it. The Engine
class is the nested class, and we can access its members by creating an object of the Car
class and then using the dot operator to access the Engine
class.
public class Car
{
public class Engine
{
public void Start()
{
Console.WriteLine("Engine started.");
}
}
}
Accessing Members of Nested Classes
To access members of nested classes, you need to create objects of both the outer and inner classes. Once you have these objects, you can use the dot operator to access members of each class. For instance, in our Car
and Engine
example, we can create objects sportsCar
and petrolEngine
to access methods of each class.
Car sportsCar = new Car();
Car.Engine petrolEngine = sportsCar.new Engine();
petrolEngine.Start(); // Output: Engine started.
Accessing Outer Class Members from Inner Classes
But what if you need to access members of the outer class from within the inner class? The answer lies in using an object of the outer class. By doing so, you can access fields and methods of the outer class from within the inner class.
public class Car
{
private string color;
public class Engine
{
public void PrintCarColor(Car car)
{
Console.WriteLine("Car color: " + car.color);
}
}
}
Accessing Static Members of Outer Classes
When it comes to accessing static members of the outer class, you don’t need to create an object of the outer class. Instead, you can directly use the name of the outer class to access its static members.
public class Car
{
public static string Manufacturer = "Toyota";
public class Engine
{
public void PrintManufacturer()
{
Console.WriteLine("Manufacturer: " + Car.Manufacturer);
}
}
}
Inheriting from Outer and Inner Classes
Just like regular classes, you can inherit from both outer and inner classes. This allows you to reuse code and create a more hierarchical structure in your program. For example, you can derive a Laptop
class from a Computer
class, or inherit an Engine
class from a CPU
class.
public class Computer
{
public class CPU
{
//...
}
}
public class Laptop : Computer
{
public class Engine : Computer.CPU
{
//...
}
}