IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Template-Method-Pattern :👈 | 👉:Terms_Of_Use |
CRTP (Curiously Recurring Template Pattern) in C# |
The Curiously Recurring Template Pattern (CRTP) is a design technique where a class uses itself as a parameter to a generic base class. It’s more common in C++, but C# supports a similar approach using generics with constraints.
A base class defines behavior that depends on the derived class type.
This allows:
using System;
// Base class using CRTP
public abstract class BaseViewModel<T> where T : BaseViewModel<T>
{
public void Initialize()
{
Console.WriteLine($"{typeof(T).Name} initializing...");
((T)this).OnInitialize(); // Call derived implementation
}
// Derived class must implement
protected abstract void OnInitialize();
}
// Derived ViewModel
public class UserViewModel : BaseViewModel<UserViewModel>
{
protected override void OnInitialize()
{
Console.WriteLine("UserViewModel: Loading user data...");
}
}
public class ProductViewModel : BaseViewModel<ProductViewModel>
{
protected override void OnInitialize()
{
Console.WriteLine("ProductViewModel: Loading product catalog...");
}
}
class Program
{
static void Main()
{
var userVM = new UserViewModel();
userVM.Initialize();
var productVM = new ProductViewModel();
productVM.Initialize();
}
}
UserViewModel initializing... UserViewModel: Loading user data... ProductViewModel initializing... ProductViewModel: Loading product catalog...
In MVVM frameworks (like .NET MAUI or WPF), CRTP can be used for a BaseViewModel lifecycle:
BaseViewModel<T> defines lifecycle hooks (Initialize, OnDestroy).UserViewModel, ProductViewModel) enforces type safety and lifecycle consistency.| Template-Method-Pattern :👈 | 👉:Terms_Of_Use |