So when should i use inheritance? Give me a real example.
- User
So when should i use inheritance? Give me a real example.
- Assistant
🏆 When inheritance really shines
Composition is usually the first choice, but inheritance is still the right tool when you have all of the following:
- A clear and stable “is-a” relationship that is unlikely to change (a Car is a Vehicle, a JwtHandler is an AuthenticationHandler, etc.).
- You want to reuse non-trivial code that lives in the base class (not just an interface contract).
- The framework you’re integrating with expects a subtype of a specific base class (ASP.NET Core has many of these extension points).
- You only need to vary a small part of the algorithm while keeping the rest intact (Template-Method pattern).
If those boxes are ticked, inheritance makes your life easier and your code smaller.
Real ASP.NET Core example: A custom
AuthorizationHandlerASP.NET Core’s authorization system is explicitly built around inheritance: every requirement handler must derive from
AuthorizationHandler<TRequirement>.
Here composition alone won’t help—you have to inherit to hook into the framework.1. Define your requirement
public class MinimumAgeRequirement : IAuthorizationRequirement { public int MinimumAge { get; } public MinimumAgeRequirement(int minimumAge) => MinimumAge = minimumAge; }2. Inherit from
AuthorizationHandler<TRequirement>public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement> { protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, MinimumAgeRequirement requirement) { // (1) Get the user's date of birth from a claim var dobClaim = context.User.FindFirst("dob"); if (dobClaim == null) return Task.CompletedTask; var dateOfBirth = DateTime.Parse(dobClaim.Value); var age = DateTime.Today.Year - dateOfBirth.Year; // (2) If the user is old enough, mark requirement as succeeded if (age >= requirement.MinimumAge) context.Succeed(requirement); return Task.CompletedTask; } }AuthorizationHandler<TRequirement>already knows how to:- register itself in the pipeline,
- loop through multiple requirements,
- expose
context.Succeed/Fail.
You only override one method (
HandleRequirementAsync) to inject your custom rule—the archetypal Template-Method use-case.3. Register and use
builder.Services.AddAuthorization(opts => { opts.AddPolicy("AtLeast21", policy => policy.Requirements.Add(new MinimumAgeRequirement(21))); }); builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();Now any controller or Razor page can do:
[Authorize(Policy = "AtLeast21")] public IActionResult OrderBeer() => Ok("🍺 Cheers!");Without inheritance you’d have to rewrite all the surrounding glue code that the base class already gives you for free.
Other day-to-day inheritance spots in ASP.NET Core
Scenario Base class you inherit Why inheritance is the correct hook Custom authentication scheme AuthenticationHandler<TOptions>Supplies challenge/forbid plumbing Custom exception handling filter ExceptionFilterAttributeFramework discovers it via attribute inheritance Custom model binder ModelBinderAttribute+IModelBinderThe attribute must derive from a base attribute Custom Tag Helper TagHelperBase class gives you HTML generation helpers Unit-of-work controller base ControllerBaseShare common logic across multiple controllers
Quick checklist before you subclass 📝
- Does “Subclass is-a BaseClass” make sense in domain language?
- Is the base class part of a framework-mandated extension point?
- Will overriding one or two methods suffice, and the rest of the algorithm should remain intact?
- Are you okay with the tight coupling (e.g., you can’t swap the base class at runtime)?
If yes ➜ inheritance is probably the right call.
If no ➜ favour composition (interfaces + DI).
TL;DR
Use inheritance when you need to plug into an existing framework hook or share a complex, stable algorithm—like writing a custom
AuthorizationHandlerin ASP.NET Core. Everywhere else, lean toward composition for flexibility and testability.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.