Author:
Private and Sealed Classes⚓︎
Private Class⚓︎
In C#, a class with the private access modifier:
- It cannot be referenced from outside the containing class.
When to use private classes?
private class only makes sense in this nested-type scenario. - In C#, a class can declare another class inside it. This is called a nested class.
public class ReportBuilder
{
// `Draft` is only used by `ReportBuilder`, so keeping it private is reasonable.
private class Draft
{
public string Title { get; set; } = string.Empty;
}
public Report BuildReport()
{
var draft = new Draft { Title = "Annual Report" };
return new Report(draft.Title);
}
}
Sealed Class⚓︎
In C#, a class with the sealed modifier:
- cannot be inherited by any other class.
private sealed Class⚓︎
The combination of private and sealed modifiers on a class usually means the type is a nested implementation detail: it is only visible inside the containing class, and it cannot be inherited. This is typically used for:
- 状态对象
- State holder objects
- Helper / implementation details
- Internal logic that is not intended to be tested, mocked, or inherited
Simple Examples⚓︎
Example 1: state holder⚓︎
public class OrderProcessor
{
private sealed class ProcessingState
{
public int RetryCount { get; set; }
public bool IsCompleted { get; set; }
}
public void Process()
{
var state = new ProcessingState();
state.RetryCount++;
}
}