Volume 1 · Chapter 10 — Modern C# and .NET Foundations

Enterprise C# Practices

Goutham Mayaluri 9 min read .NETC#

10.1 Introduction

Enterprise development is not just writing code that works - it is building systems that remain understandable, testable, secure, and adaptable as business requirements change over years. The difference between junior and senior engineering is largely the ability to make good trade-offs between simplicity, flexibility, performance, and long-term maintenance cost. This chapter covers the practices - SOLID, clean code, error handling, observability, and domain modeling - that keep enterprise C# maintainable. (Volume 6 covers SOLID and DDD in architectural depth.)

10.2 SOLID in Real Systems

SOLID is five principles that push code toward low coupling and high cohesion.SRP: a class has one reason to change (don’t mix business logic, persistence, and notification).OCP: extend behavior through new implementations, not by editing stable code.LSP: subtypes must honor their base type’s contract.ISP: prefer small, focused interfaces.DIP: depend on abstractions, not concretes.


// SRP + OCP + DIP: one responsibility each, extend via new implementations, depend on abstractions.
public interface IPaymentProcessor { Task ProcessAsync(Payment p, CancellationToken ct); }
public sealed class CreditCardProcessor : IPaymentProcessor { /* ... */ }
public sealed class WalletProcessor : IPaymentProcessor { /* new provider, no edits to existing code */ }

public sealed class Checkout
{
    private readonly IPaymentProcessor _processor;   // depends on abstraction (DIP)
    public Checkout(IPaymentProcessor processor) => _processor = processor;
}

10.3 Clean Code and Exception Handling

Clean code uses meaningful names, small focused methods, no duplicated logic, cohesive classes, and composition over inheritance. Exception handling should be consistent: don’t use exceptions for normal control flow, log failures with context (but never sensitive data), create meaningful custom exceptions, and handle errors at appropriate boundaries.


try
{
    await ProcessPaymentAsync(payment, ct);
}
catch (PaymentException ex)
{
    _logger.LogError(ex, "Payment {PaymentId} failed", payment.Id);  // context, no secrets
    throw;   // let it bubble to the boundary that decides the response
}

10.4 Observability and Domain Modeling

Production systems need visibility - logs, metrics, and traces together (observability). And enterprise code benefits from modeling around business concepts (entities, value objects, aggregates, domain services, bounded contexts) rather than technical structures, so the code speaks the language of the business and change stays localized.

flowchart LR
  App["Application"] --> Logs["Structured Logs (why)"]
  App --> Metrics["Metrics (what/how much)"]
  App --> Traces["Distributed Traces (where)"]
  Logs --> Obs["Observability"]
  Metrics --> Obs
  Traces --> Obs
Senior Interview Question

How do the SOLID principles help a large enterprise codebase in practice?

At scale, the dominant cost is changing the system safely across many teams over years, and SOLID attacks that directly by reducing coupling and increasing cohesion. Single Responsibility keeps each class focused on one reason to change, so a change to, say, notification logic doesn’t risk breaking persistence or business rules that happened to live in the same class - changes stay local. Open/Closed lets you add new behavior (a new payment provider, a new report format) by adding new implementations rather than editing stable, tested code, which reduces the blast radius and regression risk of change. Liskov Substitution keeps polymorphism safe so abstractions can be trusted - a subtype won’t surprise callers - which is what makes extension via interfaces reliable. Interface Segregation keeps interfaces small and focused so consumers depend only on what they use, avoiding coupling to methods they don’t need and making the code easier to implement and test. Dependency Inversion has high-level logic depend on abstractions, which decouples business logic from infrastructure, enables swapping implementations (and test doubles), and is the basis of dependency injection. Together the effect is that the blast radius of a change shrinks, components can be tested in isolation, new behavior is added without editing existing code, and independent teams can work in parallel without stepping on each other - exactly what a large, long-lived codebase needs. The caveat, which shows seniority, is that SOLID is a set of heuristics to apply with judgment, not dogma: over-applied it produces needless indirection, so I use it where a design is genuinely brittle or a concern genuinely volatile, and keep simpler code where it isn’t.

Senior Interview Question

What are good exception-handling practices in enterprise applications?

Good exception handling is consistent, informative, and secure. First, don’t use exceptions for normal control flow - they’re for exceptional conditions, and using them for expected outcomes is slow and obscures logic (return results or use result types for expected failures). Second, log failures with enough context to diagnose them - correlation/trace id, key identifiers, the operation - but never log sensitive data (passwords, tokens, full card numbers, personal data), because logs flow to central stores and are a common leak vector. Third, create meaningful custom exceptions for domain conditions (e.g.InsufficientFundsException) so callers can handle specific cases and the intent is clear, rather than throwing generic exceptions. Fourth, handle errors at the appropriate boundary rather than catching everywhere: let exceptions propagate to a well-defined place (a global exception handler / middleware in an API) that decides the response, logs consistently, and returns a safe error to the client without leaking internal details or stack traces. Fifth, don’t swallow exceptions silently - either handle them meaningfully or let them bubble; catching and ignoring hides bugs. Sixth, preserve stack traces when rethrowing (usethrow;, notthrow ex;) and consider wrapping lower-level exceptions with context. Finally, useusing/try-finally so resources are released even on error. The overall goal is that failures are observable and diagnosable (rich, contextual, centralized logging), safe (no sensitive data leaked, no internal details exposed to clients), and handled at the right level, rather than scattered, inconsistent try/catch that hides problems.

Principal Engineer Question

How do you balance clean architecture and good practices against delivery speed?

I resolve it by applying architectural discipline proportionally - investing in structure where it reduces the total cost of change and keeping things simple where it doesn’t - rather than treating clean architecture as either a luxury to skip or a purity to maximize. The insight is that good practices exist to lower long-term maintenance cost and change risk, so they pay off most in the parts of the system that are complex, long-lived, and change often (the core domain), and pay off least in simple, stable, or throwaway code. So I introduce abstractions, layering, and patterns where they solve a real problem - protecting a volatile business rule, enabling testing, decoupling from infrastructure that will change - and I deliberately keep simple code simple (a straightforward CRUD feature doesn’t need aggregates, repositories, and CQRS). Over-engineering - adding layers, interfaces-per-class, and patterns speculatively - actually slows delivery and adds cost without benefit, so avoiding it is itself part of balancing speed and quality. I also recognize that clean structure oftenspeeds updelivery over any meaningful horizon, because well-separated, tested code is faster and safer to change, so the trade-off is rarely “clean vs fast” in the long run - it’s mostly about not gold-plating early. Practically, I lean on enabling infrastructure (good tests, CI, paved-road patterns) so the clean path is also the fast path, I make pragmatic short-term trade-offs consciously and track them as debt to pay down, and I let the code’s complexity and change frequency guide how much structure it warrants. The mark of seniority is knowing where to spend the architectural investment and where simplicity is the right answer - which delivers both speed now and maintainability later, rather than sacrificing one for the other.

10.5 Production Scenario

A large banking application has accumulated years of tightly coupled code where every change touches multiple modules. The team improves it incrementally: introducing clear boundaries and dependency inversion so modules depend on abstractions, modeling the core domain around business concepts, adding automated tests to make refactoring safe, and applying SOLID where the code is genuinely brittle - while keeping simpler areas simple. Change velocity and reliability improve without a risky big-bang rewrite.

Volume 1 Summary and Interview Rapid-Fire

  • CLR execution model and JIT/tiered compilation
  • Memory management: stack, heap, value/reference types, boxing, IDisposable
  • Garbage collection internals and diagnostics
  • Advanced C#: generics, LINQ, expression trees, records, Span
  • Async/await internals and the thread pool
  • Threading, concurrency, races, and deadlocks
  • Reflection, metadata, and source generators
  • Performance engineering, measured first
  • Modern runtime features: R2R, Native AOT, trimming
  • Enterprise practices: SOLID, clean code, observability
Rapid-Fire Interview Question

Does the JIT compile everything at startup?

No - methods are compiled lazily on first use (Tier 0), and hot methods are recompiled optimized (Tier 1).

Rapid-Fire Interview Question

Where do value vs reference types live?

Reference types on the heap; value-type locals on the stack or inline in a heap object - boxing puts a value type on the heap.

Rapid-Fire Interview Question

Why keep objects short-lived?

So they die in cheap Gen 0 collections and never get promoted to expensive Gen 2 - reducing GC pauses.

Rapid-Fire Interview Question

Does async/await create a thread?

No - it releases the thread during I/O waits for scalability; it doesn’t spawn threads or run faster.

Rapid-Fire Interview Question

Why never use .Result/.Wait() on async?

It deadlocks with a synchronization context and starves the thread pool under load.

Rapid-Fire Interview Question

Deferred execution in one line?

A LINQ query runs when enumerated, not when defined - so materialize once before multiple enumerations.

Rapid-Fire Interview Question

Reflection vs source generators?

Reflection discovers at runtime (flexible, slower, not AOT-friendly); source generators emit code at compile time (faster, trimmable, AOT-ready).

Rapid-Fire Interview Question

First rule of performance?

Measure before optimizing - profile to find the real bottleneck, then fix and re-measure.

Rapid-Fire Interview Question

ReadyToRun vs Native AOT?

R2R precompiles the startup path but keeps the JIT; Native AOT compiles everything and removes the JIT for fastest startup and smallest footprint.

Rapid-Fire Interview Question

Single Responsibility Principle in one line?

A class should have one reason to change - keep responsibilities separate so change stays local.