Partial Classes, Extension Methods, and Static Classes
On this page
Advanced Class Structures
Beyond standard classes, C# provides three specialized structures that allow for cleaner code organization, non-intrusive library enhancement, and high-performance utility management.
1. Partial Classes: Team Collaboration
A partial class allows you to split a single class definition across multiple files. This is essential for Code Generation.
- User.cs: Contains your hand-written business logic.
- User.Generated.cs: Contains machine-generated database mapping code.
2. Extension Methods: "Retrofitting" Code
Extension methods allow you to add new methods to an existing type (like string or int) WITHOUT modifying the original source code or using inheritance.
public static class StringExtensions
{
// The 'this' keyword is the magic sauce!
public static bool IsValidEmail(this string s) => s.Contains("@");
}
// Usage:
string myEmail = "sandeep@example.com";
if (myEmail.IsValidEmail()) { ... }
3. Static Classes: The Utility Powerhouse
A static class cannot be instantiated. It is purely a container for global logic (e.g., Math or Console). Static members are shared across the entire application and live for its entire duration.
4. Interview Mastery
Q: "Where are static variables stored in memory, and are they thread-safe?"
Architect Answer: "Static variables are stored in a special segment of the Heap called the 'High Frequency Heap' (or the Metadata segment in modern .NET). They are NOT automatically thread-safe. If two threads simultaneously increment a static `Counter` variable, you will suffer from a Race Condition. You must use `lock` or `Interlocked` methods to manage concurrency for static data."