A focused C# interview set for backend developers. Each answer includes the reasoning interviewers expect, and many include small code examples you can discuss out loud.
1What does a private constructor prevent in C#, and when would you use one?
A private constructor prevents code outside its permitted private-access scope from invoking that particular constructor through normal C# access. If all constructors are private, ordinary outside code cannot instantiate the class directly, but the class can still create instances internally. Another public constructor would still allow construction. I would use this to enforce named factories and validation, control instances, or implement a carefully synchronized singleton when a singleton is genuinely appropriate. A private constructor also prevents ordinary external derived classes from calling it; it is not a replacement for sealed if preventing inheritance is the actual design goal. For a utility type that should never have instances, a static class communicates the intent more clearly. Private accessibility is an API constraint, not a security boundary against privileged reflection or specialized serialization mechanisms.
2Can a concrete C# class introduce a method with no implementation using the abstract modifier?
No. A concrete C# class cannot declare an abstract method with no implementation; the containing class must also be abstract. For example, abstract class Shape { public abstract double Area(); } is valid, and a concrete derived class must provide the required override. If the class must remain concrete, the method needs an implementation; it can be virtual if derived classes should be able to replace that behavior. An interface is another way to express a required operation independently of one base-class hierarchy. Merely writing a method that throws NotImplementedException does not make it abstract: that class can still be instantiated, and the failure occurs at runtime. I would choose the declaration based on whether incomplete instances should be forbidden at compile time.
Both ref and out give the method access to the caller's variable rather than a copy of its value. With ref, the variable must already be definitely assigned, and the method can read or replace its current value. With out, the caller need not initialize it, and the method must assign it on every normal return path before it can be used as an output. Ref suits an input/output operation; out is common in TryParse-style methods that return success plus a parsed value. The modifiers are explicit at the declaration and call site, with out also allowing a declaration such as out var value. For a reference type, ordinary value passing already permits mutation of the referenced object; ref/out additionally permit replacing the caller's reference itself. Choose a tuple or result object when that produces a clearer multi-value API.
void Increment(ref int value) => value++;
bool TryRead(string text, out int value) =>
int.TryParse(text, out value);
double Length(in Vector vector) =>
Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y);
Boxing wraps a value type into a reference-typed object by allocating an object and copying the value into it. Unboxing extracts the value back and requires the exact compatible type. Frequent boxing adds allocations and garbage-collector pressure. Generics avoid many boxing cases because List<int> stores int values without converting each value to object.
int number = 42;
object boxed = number; // boxing
int restored = (int)boxed; // unboxing
object value = 42;
// long wrong = (long)value; // InvalidCastException
long ok = (long)(int)value;
5What are nullable value types and nullable reference types?
Nullable value types use Nullable<T> or T? and represent a real runtime wrapper for value types. Nullable reference types are mostly compiler analysis: string? tells the compiler a reference may be null, but it does not create a new runtime type. The null-forgiving operator ! only suppresses warnings; it does not protect from NullReferenceException.
int? age = null;
string name = "Alice";
string? optionalName = null;
var length = optionalName?.Length;
var actualName = optionalName ?? "Unknown";
optionalName ??= "Default";
string trusted = optionalName!;
6How do const, readonly and static readonly differ?
const is a compile-time constant limited to primitives, enum values, string or null, and its value is substituted into consuming assemblies during compilation. readonly is an instance field that can be assigned in a declaration or constructor. static readonly is one field per type, assigned in a declaration or static constructor. Public values that may change across library versions are safer as static readonly than public const, because clients can keep an old inlined const until they are recompiled.
public const int MaxAttempts = 3;
private readonly Guid _id = Guid.NewGuid();
public static readonly TimeSpan Timeout =
TimeSpan.FromSeconds(30);
For ordinary classes, Equals and == compare references by default. Many built-in types and records compare by value. If Equals is overridden, GetHashCode must be consistent: if a.Equals(b) is true, both objects must have the same hash code. The reverse is not guaranteed. Never mutate fields used by equality or hashing while the object is a Dictionary key or HashSet element.
public sealed class User : IEquatable<User>
{
public required int Id { get; init; }
public bool Equals(User? other) =>
other is not null && Id == other.Id;
public override bool Equals(object? obj) =>
obj is User other && Equals(other);
public override int GetHashCode() =>
Id.GetHashCode();
}
override changes virtual behavior, so the method called depends on the runtime type of the object. new hides a member from the base class, and the selected member depends on the static type of the variable. For polymorphism you normally want virtual and override; hiding with new is less common and can make behavior confusing.
class Base
{
public virtual void First() => Console.WriteLine("Base.First");
public void Second() => Console.WriteLine("Base.Second");
}
class Derived : Base
{
public override void First() => Console.WriteLine("Derived.First");
public new void Second() => Console.WriteLine("Derived.Second");
}
Base value = new Derived();
value.First(); // Derived.First
value.Second(); // Base.Second
9How does an abstract class differ from an interface?
An abstract class can contain state, constructors, fields, implemented methods, abstract methods and protected members. An interface describes a contract; modern interfaces can include default implementations and static abstract members, but they are still not the normal place for instance state. A class can inherit one base class but implement multiple interfaces. Use an abstract class for a shared base and shared implementation; use an interface for capabilities and boundaries.
public interface IAsyncRepository<T>
{
Task<T?> FindAsync(
int id,
CancellationToken cancellationToken);
}
10Which collection would you use for a phone book, and why?
I would first clarify whether the main operation is finding a known contact, browsing alphabetically, or searching a name prefix. For exact lookup by a unique key, Dictionary<TKey,Contact> is a good default, with expected constant-time lookup, insertion and removal. I would give contacts stable IDs rather than assume names are unique. A Contact holds its display name and a collection of phone-number records, including labels such as mobile or work. If lookup by name is needed, a separate Dictionary<string,List<ContactId>> can map a normalized name to all matching contacts instead of overwriting duplicates. I would choose an explicit comparison policy, such as an appropriate case-insensitive comparer, and preserve the original display text. For occasional alphabetical display I would sort a view; for frequently maintained key order, a SortedDictionary offers logarithmic operations. Prefix or substring search may justify a separate search index. The collection choice therefore follows access patterns, not the phone-book label alone.
Covariance lets code use a more specific type where a more general produced type is expected, such as IEnumerable<string> as IEnumerable<object>. It is marked with out on interfaces and delegates. Contravariance goes the other direction for consumed values and is marked with in. Variance works only for interfaces and delegates with reference types; IEnumerable<int> cannot become IEnumerable<object> because that would require boxing, and List<string> is not assignable to List<object>.
12How does IEnumerable<T> differ from IQueryable<T>?
IQueryable<T> exposes a provider-backed expression tree, so additional filters, ordering and projection can be composed and translated to SQL before execution. IEnumerable<T> promises enumeration; LINQ-to-Objects operators operate on yielded objects rather than extending the provider's query expression. Neither interface by itself means results are already materialized: an IEnumerable can still enumerate a deferred database query. AsEnumerable changes which subsequent operators are selected without necessarily executing immediately; ToList materializes. A service may keep IQueryable internally for efficient server-side composition and return materialized DTOs or a controlled stream at its boundary. Exposing IQueryable publicly leaks provider capabilities, translation failures and context lifetime, and lets consumers accidentally create expensive or unauthorized query shapes. Choose the contract deliberately, apply required filters before crossing the boundary and verify generated SQL and resource disposal rather than assuming one interface is always faster.
Many LINQ operators build a query without executing it immediately. Execution starts when the query is enumerated or when a terminal operation such as ToList, Count or First is called. This means source changes before enumeration can affect results, repeated enumeration can repeat work or SQL queries, and exceptions may occur during enumeration rather than query construction.
var query = numbers.Where(x => x > 10);
numbers.Add(42);
foreach (var number in query)
{
Console.WriteLine(number);
}
var materialized = query.ToList();
14How do array, List<T>, Dictionary<TKey,TValue> and HashSet<T> differ?
An array has fixed size and fast indexed access. List<T> is a dynamic array with O(1) indexed access; Add at the end is amortized O(1) because growing capacity allocates a larger array and copies existing elements, while insertion in the middle is O(n). Dictionary<TKey,TValue> maps keys to values and usually provides O(1) key lookup. HashSet<T> stores unique elements and is ideal for membership checks. For hash-based collections, correct Equals and GetHashCode implementations are essential.
var ids = new HashSet<int> { 1, 2, 3 };
if (ids.Contains(userId))
{
// Fast membership check
}
15How do IEnumerable<T>, ICollection<T>, IList<T> and IReadOnlyCollection<T> differ?
IEnumerable<T> promises only sequential enumeration. ICollection<T> adds Count and mutation methods such as Add and Remove. IList<T> adds indexed access. IReadOnlyCollection<T> exposes enumeration and Count but not mutation through that interface. API design should return the narrowest useful contract, but read-only interfaces do not guarantee deep immutability of the underlying object.
yield return creates an iterator with deferred execution. The compiler transforms the method into a state machine, and values are produced one by one when MoveNext is called. This avoids intermediate collections and works well for large sequences. The traps are lifetime and multiple enumeration: do not return a lazy sequence that depends on a disposed DbContext or stream, and remember that Count followed by foreach can execute the iterator twice, repeating side effects or I/O.
IEnumerable<int> GetEvenNumbers(IEnumerable<int> source)
{
foreach (var number in source)
{
if (number % 2 == 0)
yield return number;
}
}
17What is a delegate in C#, and how do you declare and invoke one?
A delegate is a callable object with a declared signature that refers to a method and, for an instance method, its target object. It can represent a static method, instance method or a compatible lambda, and delegates can also contain an invocation list for multicast calls. When a method group or lambda is assigned, the compiler checks compatibility with the delegate's parameter types, parameter modifiers and return type, including permitted variance and conversion rules. For example, Func<int, int> can hold a function that accepts an int and returns an int, while Action<string> represents a void-returning operation on a string. This allows callbacks to be passed without naming a concrete implementation. The checks establish type compatibility, not business correctness, thread safety, execution time or absence of exceptions. Captured objects can remain alive as long as the delegate references them. For example, declare Func<int, int> transform = Math.Abs and invoke it with transform(-3).
using System;
public delegate void Logger(string message);
public class Program
{
public static void LogToConsole(string msg) => Console.WriteLine($"Console: {msg}");
public static void LogToFile(string msg) => Console.WriteLine($"File: {msg}");
public static void Main()
{
// Assign method using method group conversion
Logger log = LogToConsole;
// Multicast: chaining another method
log += LogToFile;
// Invoking the delegate
log("System initialized");
}
}
An event is usually backed by a delegate, but it restricts what outside code can do. External code can subscribe and unsubscribe, but only the owner class can raise the event. A public delegate field would allow callers to replace the invocation list or invoke it directly. Events also create references from publisher to subscriber, so long-lived publishers can cause memory leaks if subscribers do not unsubscribe.
19How does the lifetime of a C# using declaration differ from a using statement with an explicit block?
With using var stream = Open();, the resource is disposed when control leaves the scope containing that declaration, which may be the entire method. With using (var stream = Open()) { ... }, disposal occurs when control leaves that explicit block, so later statements in the method run after disposal. Both forms compile to cleanup semantics comparable to try/finally and dispose on normal exit, return or exception unwinding; they do not wait for garbage collection. Multiple using declarations in one scope are disposed in reverse declaration order. I would choose an explicit block, or a smaller surrounding scope, when a file lock, transaction or other resource should be released before subsequent work. await using applies the analogous lifetime rule while awaiting asynchronous disposal. Disposal releases the resource's defined holdings; it does not necessarily make the managed object immediately disappear from memory.
Exception filters let a catch block run only when an additional condition is true. The filter is evaluated before stack unwinding and before entering the catch body, so when returns false the original stack remains intact for diagnostics and crash dumps. Filters are useful for HTTP status codes, database error codes, distinguishing transient errors and conditional logging. Keep filters simple and avoid complex side effects.
try
{
await SendAsync();
}
catch (HttpRequestException ex)
when (ex.StatusCode == HttpStatusCode.NotFound)
{
// Handle only 404
}