Information Technology
C# Interview Questions & Answers
Learn the C# programming language.
Arrays, Span<T> & Memory<T>
All 11 questionsArrays in C# have a fixed size set at creation time, declared with square brackets after the element type, and can be initialized with a collection expression or explicit 'new' syn…
- How do you create and work with a multidimensional (rectangular) array versus a jagged array? Beginner
A rectangular array (int[,]) has a fixed grid shape where every row has the same length; a jagged array (int[][]) is an array of arrays, where each inner array can have a different…
Span is a stack-only (ref struct) type representing a contiguous, type-safe view over a region of memory — it lets you slice arrays, strings, or stack-allocated memory WITHOUT copy…
Memory is a heap-allocatable counterpart to Span — since Span is a ref struct restricted to the stack (can't be used in async methods, lambdas capturing it, or as a class field), M…
Call .AsSpan() (with optional start/length arguments) on an array or string to get a Span or ReadOnlySpan view over just that portion — no new memory is allocated, unlike Substring…
Asynchronous Programming
All 20 questions- What do async and await do? Beginner
await asynchronously waits for a Task, releasing the thread until it completes, then resumes the method; async marks a method that uses await and returns a Task.
Task represents async work with no result; Task completes with a value of type T that you get by awaiting it.
Start the tasks without awaiting each immediately, then await Task.WhenAll to run them in parallel and wait for all.
- What does ConfigureAwait(false) do? Intermediate
It resumes the continuation without capturing the synchronization context, avoiding a needless hop and reducing deadlocks. Use it in library code that doesn't touch UI/HttpContext.
In a single-threaded context the blocked thread waits for a continuation that needs that same thread — neither proceeds. Fix by awaiting all the way down.
Attributes & Reflection
All 11 questionsAn attribute is metadata attached to a code element (class, method, property, etc.) using square-bracket syntax placed directly above it — attributes don't affect runtime behavior…
- What is reflection, and what basic information can you retrieve from a Type object at runtime? Beginner
Reflection lets you inspect metadata about types, methods, properties, and assemblies AT RUNTIME, even for types you don't have compile-time knowledge of — a Type object (obtained…
Define a class that inherits from System.Attribute (conventionally suffixed with "Attribute", though C# lets you omit the suffix when applying it); the [AttributeUsage] attribute o…
- How do you use reflection to read a custom attribute's values off a property at runtime? Intermediate
Use GetCustomAttribute () (or GetCustomAttributes for multiple) on a PropertyInfo, MethodInfo, or Type object to retrieve an instance of the applied attribute, then read its proper…
Activator.CreateInstance(type) constructs a new instance given a Type object (optionally with constructor arguments), and MethodInfo.Invoke(instance, args) calls a method on that i…
Collections
All 16 questionsUse an array for a fixed-size, performance-critical buffer; use List when the count changes, since it grows and offers Add/Remove/Insert.
When you need fast key-based lookups (O(1) average). Keys are unique; use TryGetValue to avoid exceptions on missing keys.
IEnumerable supports iteration only; ICollection adds Count/Add/Remove; IList adds indexed access and Insert. Accept the least specific type your method needs.
- What does HashSet<T> provide and when do you use it? Intermediate
A set of unique elements with fast Contains/Add and set operations. Adding a duplicate is a no-op.
Use ConcurrentDictionary for thread-safe reads/writes without external locks; use ImmutableList/Dictionary when you want safe sharing across threads via copy-on-write snapshots.
Delegates, Events & Lambdas
All 17 questions- What is a delegate in C#? Beginner
A delegate is a type-safe reference to a method, letting you pass behaviour as a parameter and invoke it later. Func<>, Action<> and Predicate<> are built-in delegates.
Func returns a value; Action returns void; Predicate is a Func used for tests.
- What is a closure and what is a common pitfall? Intermediate
A closure is a lambda that captures variables from its enclosing scope. A classic pitfall is capturing a loop variable by reference so all lambdas see its final value.
- How do events differ from plain delegates? Intermediate
An event is a delegate wrapped so external code can only subscribe (+=) or unsubscribe (-=), not invoke or overwrite it — enforcing the publisher/subscriber boundary.
A long-lived publisher holding a delegate to a subscriber keeps the subscriber alive. Prevent it by unsubscribing (-=), using weak event patterns, or scoping lifetimes.
Dependency Injection & IoC Principles
All 10 questionsDependency injection means a class RECEIVES its dependencies (typically via constructor parameters) from an external source, rather than constructing them itself with 'new' — this…
Register a service's interface-to-implementation mapping in Program.cs using builder.Services.AddXxx(), then ASP.NET Core automatically INJECTS it into any controller or class cons…
- What is the difference between Singleton, Scoped, and Transient service lifetimes in ASP.NET Core's DI container? Intermediate
Singleton creates ONE instance for the entire application's lifetime, shared across all requests; Scoped creates ONE instance PER REQUEST (or per logical scope), shared within that…
IoC is the broader principle that a component should NOT control the creation/lifecycle of its own dependencies — control is 'inverted' to an external source (a framework, containe…
Constructor injection passes dependencies through the constructor, guaranteeing an object is NEVER in a partially-initialized state and making dependencies clearly visible in the c…
Design Patterns in C#
All 11 questionsLazy defers creation of the instance until it's first accessed AND guarantees thread-safe initialization by default, making it the cleanest modern way to implement a Singleton with…
A Factory Method encapsulates object-creation logic behind a method (often on a base class or interface) that subclasses or implementations override to decide WHICH concrete type t…
- How would you implement the Strategy pattern in C# using either interfaces or delegates? Intermediate
Define a common interface (or a delegate type) representing an interchangeable algorithm, implement multiple concrete strategies, and inject/pass the chosen one into the context cl…
- How does the Repository pattern abstract data access, and what interface typically defines its contract? Intermediate
The Repository pattern defines an interface (like IRepository ) exposing domain-focused CRUD operations, hiding the underlying data access technology (Entity Framework, raw SQL, an…
Create a decorator class that implements the SAME interface as the object it wraps, holds a reference to the wrapped instance, and adds behavior before/after delegating the actual…
Enums & Flags
All 10 questionsAn enum is a distinct value type representing a named set of constant integral values; by default, its members are backed by 'int', starting at 0 and auto-incrementing, unless you…
Cast directly with (int) to get the numeric value; use ToString() to get the member's name as a string, and Enum.Parse () (or the safer Enum.TryParse ()) to convert a string back i…
- How do you create a 'flags' enum that supports combining multiple values using bitwise operations? Intermediate
Mark the enum with [Flags] and assign each member a distinct POWER-OF-TWO value, letting you safely combine multiple flags into a single value with the bitwise OR operator and chec…
- How does the [Flags] attribute change the output of ToString() on a combined flags enum value? Intermediate
Without [Flags], calling ToString() on a value that doesn't exactly match any single named member just returns the raw numeric value as a string; WITH [Flags], the runtime recogniz…
- What is the performance consideration when using Enum.HasFlag() versus a direct bitwise AND check? Intermediate
Enum.HasFlag() involves BOXING the enum value (converting it to an object) internally in older .NET versions, making it measurably slower than a direct bitwise AND comparison in pe…
Equality: Equals, GetHashCode & IEquatable
All 10 questionsFor a reference type without overrides, both == and the inherited Object.Equals() check REFERENCE equality — whether two variables point to the exact SAME object in memory — not wh…
- How does a struct's default Equals() behavior differ from a class's, even without any overrides? Beginner
System.ValueType (the base for all structs) overrides Equals() to perform FIELD-BY-FIELD value comparison by default (via reflection, which is slower than a hand-written override),…
.NET's contract requires that if two objects are Equal() (return true), they MUST also return the SAME GetHashCode() value — hash-based collections like Dictionary and HashSet rely…
IEquatable .Equals(T other) provides a STRONGLY-TYPED equality method that avoids the boxing (for structs) and the type-checking/casting overhead that Equals(object) requires — man…
- How does HashCode.Combine() help you write a correct and well-distributed GetHashCode() implementation? Intermediate
HashCode.Combine() takes multiple field values and produces a well-mixed, evenly-distributed hash code using a proven algorithm — far better than naive approaches like simply XOR-i…
Exception Handling
All 16 questionsthrow re-throws preserving the original stack trace; throw ex resets the stack trace to the current line, losing where the error really happened.
finally always runs (whether or not an exception occurred) and is used to release resources like files, connections or locks.
- When should you use using or await using? Intermediate
For IDisposable/IAsyncDisposable resources — they call Dispose/DisposeAsync deterministically at the end of scope, even on exceptions, replacing manual try/finally.
- What are exception filters (when) and why use them? Intermediate
A when clause lets a catch run only if a condition is true, without unwinding the stack for non-matching cases, which aids logging and selective handling.
Create a custom exception when callers need to catch a domain-specific condition distinctly; otherwise reuse built-ins (ArgumentException, InvalidOperationException). Keep a meanin…
Extension Methods
All 11 questionsAn extension method lets you 'add' new methods to an existing type (even one you don't own the source for, like a built-in .NET type) without modifying it — declared as a static me…
Extension methods are purely a COMPILE-TIME convenience — the compiler resolves 'obj.ExtensionMethod()' by rewriting it internally as 'StaticClass.ExtensionMethod(obj)', which requ…
A genuine INSTANCE method on the type ALWAYS takes priority over an extension method with a matching signature — the compiler only falls back to searching for an applicable extensi…
- How do you write a generic extension method that works with any collection type, like a custom 'IsEmpty()' check? Intermediate
Add a generic type parameter to the extension method itself (after the static method's name), constrained as needed, and use it in the 'this' parameter's type — this lets a single…
As long as each extension method RETURNS a value of a type that has further applicable extension (or instance) methods, calls can be chained one after another — this is exactly the…
File I/O & Streams
All 10 questions- How do you read and write an entire text file's contents using the simplest File class methods? Beginner
File.ReadAllText() reads an entire file's contents into a single string; File.WriteAllText() writes a string to a file, creating it if it doesn't exist or overwriting it if it does…
- What is the difference between File.ReadAllLines() and File.ReadLines() in terms of memory usage? Beginner
File.ReadAllLines() reads the ENTIRE file and returns a fully-materialized string[] array all at once; File.ReadLines() returns a LAZY IEnumerable that reads and yields one line at…
'using' automatically calls Dispose() on the resource when execution leaves its scope — whether normally or via an exception — guaranteeing the underlying file handle is released;…
- How do StreamReader and StreamWriter differ from directly using a FileStream, and when would you choose them? Intermediate
FileStream operates on raw BYTES; StreamReader/StreamWriter wrap a Stream (like a FileStream) and add TEXT ENCODING handling (converting between bytes and characters using a specif…
CopyToAsync() efficiently transfers data from a source stream to a destination stream using an internally-managed BUFFER (reading a chunk, writing it, repeating), fully asynchronou…
Fundamentals
All 16 questionsvar uses compile-time type inference; the compiler still gives it a single static type. It is not dynamic — the type is fixed once inferred.
const is a compile-time constant embedded into callers and must be initialised inline; readonly is set once at runtime (declaration or constructor) and can vary per instance.
string overrides == and Equals to compare characters, so two strings with the same content are equal even if they are different objects.
By default integer overflow wraps silently (unchecked); a checked context throws OverflowException on overflow, which is safer for money/counters.
ref passes a variable by reference (must be initialised, can be read/written); out must be assigned inside the method (need not be initialised by caller); in passes by reference re…
Generics
All 17 questions- What are generics and why use them? Beginner
Generics let you write type-parameterised classes/methods that work with any type while keeping compile-time type safety and avoiding boxing.
Constraints (where T : ...) restrict the type argument so you can use its members — e.g. class, struct, new(), a base type, or an interface.
- What is covariance and contravariance in generics? Intermediate
out (covariant) lets you use a more-derived type where a less-derived is expected (IEnumerable ); in (contravariant) lets a less-derived be used where more-derived is expected (ICo…
The JIT creates a specialised instantiation per value type (no boxing, better perf) but shares a single instantiation for all reference types, since they are the same size (a point…
They let you write algorithms over any numeric type by constraining to interfaces like INumber with static abstract operators, removing duplicated overloads.
Indexers & Operator Overloading
All 10 questions- What is an indexer, and how does it let a custom class support square-bracket syntax like an array? Beginner
An indexer is a special property-like member defined with 'this[...]' syntax, letting instances of your class be accessed using square brackets (obj[key]) just like an array or dic…
Declare a 'public static' method named 'operator +' taking two parameters of your type (or your type and another compatible type), returning the result — the compiler then lets you…
- Which operators can be overloaded in C#, and which ones (like && and ||) generally CANNOT be overloaded directly? Intermediate
You can overload most unary and binary operators (+, -, *, /, ==, !=, , etc.), true/false, and implicit/explicit conversion operators — but && and || specifically CANNOT be overloa…
Overload ' ' as static operator methods, and their logic must be CONSISTENT with any overloaded '==' and Equals() — specifically, if a.Equals(b) is true, then neither a b should al…
- How do you define a custom implicit or explicit conversion operator between your type and another type? Intermediate
'implicit operator' lets the compiler AUTOMATICALLY convert between types without an explicit cast (used when the conversion is always safe and lossless); 'explicit operator' requi…
Interfaces & Abstract Classes
All 17 questionsAn abstract class can hold state and shared implementation and supports single inheritance; an interface is a contract a type can implement many of. Use interfaces for capabilities…
Depending on an abstraction decouples callers from implementations, enabling substitution, testing with mocks, and dependency injection.
Since C# 8 an interface can provide a default method body, letting you add members to an interface without breaking existing implementers.
Yes. If signatures clash you can implement the members explicitly, qualified by interface name, so each interface gets its own behaviour accessible via that interface type.
When you need shared state or non-trivial common implementation, versioning with protected members, or to control the construction of derived types — things interfaces cannot expre…
Iterators & yield return
All 10 questions'yield return' produces one value at a time from a sequence WITHOUT computing and storing the entire sequence upfront — the method's return type must be IEnumerable (or IEnumerator…
Code inside an iterator method DOESN'T run at all when you first call it — it only executes incrementally, ONE STEP AT A TIME, as the consumer actually requests each next value (vi…
- How would you implement a custom IEnumerable<T> on your own class using yield return, letting it support foreach? Intermediate
Implement IEnumerable on your class and provide a GetEnumerator() method (using 'yield return' internally) that produces the sequence of elements — this lets instances of your cust…
- How does 'yield break' work, and how does it differ from a plain 'return' statement inside a regular method? Intermediate
'yield break' immediately stops the iterator's sequence, signaling there are no more elements — it's the iterator equivalent of 'return' in a regular method, but specifically for t…
A finally block inside an iterator runs when iteration COMPLETES NORMALLY, when 'yield break' is hit, OR when the consumer disposes the enumerator early (like breaking out of a for…
LINQ
All 18 questionsLINQ queries collections and data sources uniformly. Most operators are lazy: the query executes when enumerated (foreach/ToList), so it reflects the latest data.
IEnumerable executes in memory (LINQ-to-Objects); IQueryable builds an expression tree a provider (EF Core) translates to SQL, so filtering happens in the database.
First returns the first match or throws if none; FirstOrDefault returns default if none; Single expects exactly one and throws otherwise.
Select projects one-to-one (giving a sequence of sequences if the selector returns a collection); SelectMany flattens those into one sequence.
GroupBy partitions by a key into IGrouping . In LINQ-to-Objects it buffers; in EF Core only certain shapes translate to SQL GROUP BY, otherwise it fails or evaluates client-side.
Memory & Garbage Collection
All 18 questionsThe GC automatically reclaims unreachable managed objects. It is generational (Gen 0/1/2): short-lived objects are collected cheaply in Gen 0, survivors are promoted.
Managed resources are handled by the GC; unmanaged resources (file handles, sockets, native memory) are not and must be released via Dispose/finalizers.
It provides deterministic cleanup of unmanaged resources via Dispose(), usually with using. Implement it when a type owns unmanaged or disposable resources.
Dispose is deterministic cleanup you call; a finalizer runs non-deterministically during GC as a safety net. Finalizers delay collection, so prefer Dispose and suppress finalizatio…
Objects stay reachable unintentionally: static references, un-removed event handlers, long-lived caches, or captured closures. The GC can't collect what is still referenced.
Modern C# Features (Global Usings, File-Scoped Namespaces, Top-Level Statements)
All 10 questionsTop-level statements (C# 9+) let you write executable code directly at the top of a .cs file WITHOUT wrapping it in an explicit Main() method or even a class — the compiler automat…
A file-scoped namespace (`namespace MyApp.Services;` with a semicolon, no braces) applies to EVERY type declared in the rest of that file, eliminating one level of nested indentati…
Prefixing a 'using' directive with 'global' (either directly in a .cs file, or conventionally in a dedicated GlobalUsings.cs file) makes that namespace available to EVERY file in t…
- What does the 'ImplicitUsings' project setting (`<ImplicitUsings>enable</ImplicitUsings>`) do automatically? Intermediate
Enabling ImplicitUsings automatically adds a curated set of GLOBAL using directives for the most commonly-needed namespaces (like System, System.Linq, System.Collections.Generic, a…
Marking a property 'required' forces callers to set it via OBJECT INITIALIZER syntax (or a constructor annotated with [SetsRequiredMembers]) — the compiler raises an error if a req…
Nullable Reference Types
All 6 questionsAn opt-in compiler feature where reference types are non-null by default and nullability is expressed with ?, giving warnings when you might dereference null.
! tells the compiler you know a value isn't null, suppressing the warning. Use it sparingly when you have knowledge the compiler lacks — overuse hides real bugs.
- What is the difference between ?., ?? and ??=? Intermediate
?. is null-conditional access (returns null instead of throwing); ?? is null-coalescing (fallback value); ??= assigns only if the target is null.
- How do nullable annotations affect API design? Intermediate
Method signatures document intent: a string? parameter accepts null, a string return promises non-null. This forms a contract callers can rely on.
They express nullability that depends on outcomes the type alone can't show, improving flow analysis for helpers like TryGet.
Encapsulation (hide state behind members), Inheritance (derive types), Polymorphism (one interface, many implementations) and Abstraction (expose essentials, hide detail).
Properties expose get/set accessors over a private field, letting you validate on set and compute on get while keeping the field hidden.
override replaces a virtual/abstract base member and uses run-time (polymorphic) dispatch; new hides the base member and dispatch depends on the compile-time type, which is usually…
- What does the sealed keyword do and why use it? Intermediate
sealed stops a class being inherited or a member being further overridden. It can protect invariants and lets the JIT devirtualise calls for speed.
Composition builds behaviour by holding other objects rather than inheriting; it avoids deep, rigid hierarchies and the fragile base-class problem. Prefer it unless there is a true…
Records & Pattern Matching
All 7 questionsA record is a reference type with compiler-generated value equality, ToString and non-destructive mutation (with). It's ideal for immutable data.
- What does the with expression do? Beginner
with creates a copy of a record with some properties changed, leaving the original unchanged (non-destructive mutation).
- What is a record struct and when would you use it? Intermediate
A record struct is a value type with record-like value semantics and equality; use it for small immutable value data where you also want stack/value copying.
- How does switch pattern matching improve code? Intermediate
switch expressions match on type, constant, relational and property patterns, returning a value concisely and forcing exhaustive, readable branching.
They deconstruct and test an object's shape in one expression, enabling clear rules over complex data without manual null checks and casts.
Value vs Reference Types
All 8 questionsValue types (struct, enum, primitives) hold their data directly and are copied on assignment; reference types (class, array, string, delegate) hold a reference to data on the heap,…
Local value types typically live on the stack; reference-type objects live on the managed heap with the reference on the stack. Value-type fields inside a class live on the heap wi…
- What is boxing and unboxing, and why does it matter? Intermediate
Boxing wraps a value type in a heap object (implicit); unboxing extracts it (explicit cast). Both allocate/copy and hurt performance in loops.
- When should you define a struct instead of a class? Intermediate
Use a struct for small, immutable, value-like data (under ~16 bytes) that is copied cheaply and has value semantics; otherwise use a class. Mutable structs are error-prone.
int? is Nullable , a struct with HasValue and Value. The compiler lifts operators so null propagates; boxing a null Nullable boxes to a real null reference.