C# Language Interview Q&A

C# Language Interview Q&A

Explore c# language interview q&a code snippets and tutorials

C# Language Interview Q&A

C# throw vs throw ex: preserving stack traces and designing exception handling

Exception filters (when) for selective catching.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// ======================================================================
// Q: throw vs throw ex? How do you design exception handling?
//
// - Exception filters (when) for selective catching. Only catch what you can
//   handle.
// - No exceptions for expected flow (e.g. "not found"). Use null, TryXxx or the
//   Result pattern there.
// - Custom exceptions for business rules (DomainException) and one central
//   IExceptionHandler that converts them to ProblemDetails (Q6).
// ======================================================================

try { await erp.SendOrderAsync(order, ct); }
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
{
    logger.LogWarning(ex, "ERP unavailable for {OrderId}", order.Id);
    throw;          // ✓ keeps the original stack trace
    // throw ex;    // ✗ the stack trace starts here: you lose where the error happened
}
C# Language Interview Q&A

C# string immutability: when to use StringBuilder vs interpolation

Every "change" to a string creates a new object.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ======================================================================
// Q: Strings are immutable. When do you use StringBuilder?
//
// Every "change" to a string creates a new object. In a loop with many appends:
// StringBuilder. For a few appends, interpolation ($"..."), which has been
// optimized since .NET 6. For case-insensitive comparison: string.Equals(a, b,
// StringComparison.OrdinalIgnoreCase), not ToLower().
// ======================================================================

var sb = new StringBuilder();
foreach (var line in order.Lines)
    sb.Append(line.Sku).Append(';').Append(line.Quantity).AppendLine();
var csv = sb.ToString();
C# Language Interview Q&A

C# extension methods: how they work and where .NET uses them (LINQ, DI)

Static methods in a static class, with this on the first parameter.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// ======================================================================
// Q: What are extension methods? Where does .NET use them?
//
// Static methods in a static class, with this on the first parameter. They add
// methods to types without modifying them. All of LINQ is extension methods, as
// are all the builder.Services.AddXxx() calls. C# 14 also has extension members
// (extension(...) blocks with properties).
// ======================================================================

public static class DependencyInjection
{
    public static IServiceCollection AddApplication(this IServiceCollection services)
    {
        services.AddScoped<PlaceOrderHandler>();
        return services;               // fluent: builder.Services.AddApplication().AddInfrastructure()
    }
}
C# Language Interview Q&A

C# generics and type constraints (where T : class, struct, new()) explained

Type safety without casting, without boxing, and code reuse.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// ======================================================================
// Q: Generics and constraints: why and how?
//
// Type safety without casting, without boxing, and code reuse. Constraints state
// what the code is allowed to do with T.
// ======================================================================

public interface IEntity { int Id { get; } }

public class Cache<T> where T : class, IEntity      // reference type that has an Id
{
    private readonly Dictionary<int, T> _items = new();
    public void Add(T item) => _items[item.Id] = item;
    public T? Get(int id) => _items.GetValueOrDefault(id);
}
// Other constraints: struct, new(), notnull, unmanaged, where T : BaseClass
C# Language Interview Q&A

C# delegates, Func, Action, events and lambdas explained

Delegate: a type that represents a method (a type-safe function pointer).

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// ======================================================================
// Q: Delegates, Func, Action, events and lambdas?
//
// - Delegate: a type that represents a method (a type-safe function pointer).
//   Func<T, TResult> returns a value, Action<T> does not, Predicate<T> returns
//   bool.
// - Lambda: short syntax for a delegate or expression tree (x => x * 2). Lambdas
//   capture variables (closures), which costs an allocation.
// - Event: a delegate that only the owning class can invoke. Others can only +=
//   / -=. A forgotten -= on a long-lived publisher = memory leak.
// ======================================================================

Func<decimal, decimal> withVat = net => net * 1.24m;
Action<string> log = msg => Console.WriteLine(msg);
log($"Total: {withVat(100)}");