Lesson 14/30

Tutorials C# Mastery

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."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals
2. Control Flow & Logical Structures
3. Object-Oriented Mastery
4. Functional C# & Collections
5. Asynchronous & Parallel Programming
6. Advanced Engineering & High Performance
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details