C# MCQ
Test your C# knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.
How This Practice Test Works
Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
1
What company developed C#?
Correct Answer
Microsoft
Explanation
C# was developed by Microsoft, led by Anders Hejlsberg, and released in 2000 as part of the .NET initiative.
2
What runtime executes C# code?
Correct Answer
CLR (Common Language Runtime)
Explanation
C# compiles to CIL (Common Intermediate Language), which is executed by the CLR, the .NET runtime.
3
How do you print to the console in C#?
Correct Answer
Console.WriteLine("Hello")
Explanation
Console.WriteLine() writes text followed by a newline. Console.Write() writes without a newline.
4
What keyword is used to declare a variable that cannot be reassigned?
Correct Answer
const
Explanation
const declares a compile-time constant. readonly allows setting in constructor only and is evaluated at runtime.
5
Which C# data type stores a sequence of characters?
Correct Answer
string
Explanation
string is an alias for System.String. It is immutable in C#.
6
What is the entry point of a C# console application?
Correct Answer
Main()
Explanation
static void Main(string[] args) or static int Main() is the entry point. In .NET 6+, top-level statements eliminate the need for Main().
7
What is a namespace in C#?
Correct Answer
A logical grouping of related types to avoid naming conflicts
Explanation
Namespaces organize code. System, System.Collections, and System.IO are examples. using System; imports all types from the namespace.
8
What does the var keyword do in C#?
Correct Answer
Lets the compiler infer the type from the initializer
Explanation
var x = 42; infers x as int. var is compile-time inference — the type is fixed. It is not dynamic like dynamic.
9
What is an interface in C#?
Correct Answer
A contract defining method and property signatures that implementing classes must fulfill
Explanation
Interfaces (IDisposable, IEnumerable) define contracts. A class can implement multiple interfaces.
10
What is the difference between class and struct in C#?
Correct Answer
Classes are reference types (heap); structs are value types (stack/inline)
Explanation
Classes are reference types; assignment copies the reference. Structs are value types; assignment copies the entire value.
11
What is a property in C#?
Correct Answer
A class member with get/set accessors providing controlled access to a backing field
Explanation
public int Age { get; set; } is an auto-property. Custom getters/setters allow validation or computed values.
12
What does the override keyword do?
Correct Answer
Provides a new implementation of a virtual or abstract method from a base class
Explanation
override redefines a virtual/abstract method with runtime polymorphism. new creates a compile-time shadow (hiding), not true overriding.
13
What is the purpose of using statement?
Correct Answer
Both imports a namespace AND manages resource disposal via IDisposable
Explanation
using System; imports a namespace. using (var f = File.Open(...)) { } disposes IDisposable resources when leaving the block.
14
What is LINQ?
Correct Answer
Language Integrated Query — a uniform query syntax for collections, databases, and XML
Explanation
LINQ enables SQL-like queries: var result = from x in list where x > 5 select x; or fluent: list.Where(x => x > 5).
15
What are generics in C#?
Correct Answer
Type-parameterized classes and methods that work with any type while maintaining type safety
Explanation
List<T>, Dictionary<TKey, TValue>, and custom generic classes provide type-safe reusability without boxing.
16
What is a delegate in C#?
Correct Answer
A type-safe function pointer that can reference methods with a matching signature
Explanation
delegate int Operation(int a, int b); declares a delegate. Methods with matching signatures can be assigned to it and invoked.
17
What is an event in C#?
Correct Answer
A notification mechanism built on delegates allowing subscribers to respond to actions
Explanation
Events use the event keyword with a delegate type. Subscribers use += to register handlers; -= to unsubscribe.
18
What does async/await do in C#?
Correct Answer
Enables non-blocking asynchronous code that reads like synchronous code
Explanation
async methods contain await expressions. await suspends the method until the awaited Task completes, freeing the thread for other work.
19
What is the null-conditional operator ?. in C#?
Correct Answer
Accesses a member only if the object is non-null; otherwise returns null
Explanation
user?.Address?.City returns null if user or Address is null without throwing NullReferenceException.
20
What is the null coalescing operator ?? in C#?
Correct Answer
Returns the left operand if non-null; otherwise returns the right operand
Explanation
string name = user.Name ?? "Anonymous"; returns user.Name if not null, otherwise "Anonymous".
21
What is an enum in C#?
Correct Answer
A value type consisting of a set of named integer constants
Explanation
enum Day { Mon, Tue, Wed } creates named constants. By default, values are ints starting at 0.
22
What is exception handling in C# using try-catch?
Correct Answer
Catches and handles exceptions in a structured way; finally always executes
Explanation
try { risky code } catch (Exception ex) { handle } finally { cleanup } — finally runs whether or not an exception was thrown.
23
What is an array in C#?
Correct Answer
A fixed-size collection of elements of the same type
Explanation
int[] arr = new int[5]; declares an array of 5 integers. Arrays are fixed-size; use List<T> for dynamic sizing.
24
What is a List<T> in C#?
Correct Answer
A dynamic, resizable generic collection
Explanation
List<T> dynamically resizes, supports Add(), Remove(), Contains(), Sort(), and many other methods.
25
What is the difference between == and .Equals() for strings in C#?
Correct Answer
For string, both check value equality because == is overloaded. Generally, == checks reference for objects
Explanation
For string specifically, C# overloads == to compare values. For general objects, == compares references. Use string.Equals(a, b, StringComparison) for culture-aware comparison.
26
What is the sealed keyword in C#?
Correct Answer
Prevents a class from being subclassed, or prevents a method from being further overridden
Explanation
sealed class MyClass prevents inheritance. sealed override void Method() prevents further overriding in subclasses.
27
What is string interpolation in C#?
Correct Answer
Embedding expressions in a string literal using $"Hello {name}"
Explanation
$"Hello, {user.Name}! You are {age} years old." compiles to string.Format() calls at compile time.
28
What is a static class in C#?
Correct Answer
A class that cannot be instantiated and contains only static members
Explanation
static class MathHelper { public static int Square(int x) => x * x; } cannot be instantiated. Used for utility/helper classes.
29
What does the base keyword do?
Correct Answer
Refers to the parent class, used to call parent constructors or overridden methods
Explanation
base.Method() calls the overridden parent method. base(args) in a constructor calls the parent constructor.
30
What is the purpose of IDisposable?
Correct Answer
Provides a Dispose() method for releasing unmanaged resources when using the using statement
Explanation
Implement IDisposable to release file handles, database connections, etc. The using statement automatically calls Dispose() at block end.
31
What is a lambda expression in C#?
Correct Answer
An anonymous function using => syntax, assignable to delegates or LINQ expressions
Explanation
Func<int, int> square = x => x * x; is a single-expression lambda. Multi-line: x => { return x * x; }.
32
What is the difference between Task and Thread in C#?
Correct Answer
Thread is a lower-level OS thread; Task is a higher-level abstraction over the thread pool supporting async/await
Explanation
Task is part of the TPL and works with async/await. Thread gives direct control but is heavier. Prefer Task for most async scenarios.
33
What is an abstract class in C#?
Correct Answer
A class that cannot be instantiated directly and may contain abstract methods subclasses must implement
Explanation
abstract class Shape { abstract double Area(); } cannot be instantiated. Derived classes must implement Area().
34
What does the as keyword do?
Correct Answer
Performs a safe type cast, returning null if the cast fails instead of throwing
Explanation
string s = obj as string; returns null if obj is not a string, unlike (string)obj which throws InvalidCastException.
35
What is boxing in C#?
Correct Answer
Converting a value type to a reference type (object) by wrapping it on the heap
Explanation
object o = 42; boxes the int 42 onto the heap. int x = (int)o; is unboxing. Excessive boxing/unboxing impacts performance.
36
What is a partial class?
Correct Answer
A class whose definition is split across multiple files using the partial keyword
Explanation
partial class MyForm { } allows splitting a large class across files. The compiler merges them. Used heavily in Windows Forms and ASP.NET codegen.
37
What is the => syntax used for in property declarations?
Correct Answer
Expression-bodied member syntax — a concise single-expression getter
Explanation
public string FullName => $"{FirstName} {LastName}"; is an expression-bodied property, equivalent to a get { return ...; } property.
38
What is the difference between Array and ArrayList in C#?
Correct Answer
Array is typed and fixed-size; ArrayList is non-generic and can hold any object (avoid in favor of List<T>)
Explanation
Array<T> is fixed-size and typed. ArrayList stores object, requiring boxing for value types. List<T> replaced ArrayList in .NET 2.0.
39
What is the this keyword in C#?
Correct Answer
Refers to the current instance of the class
Explanation
this.name = name distinguishes the instance field from the constructor parameter. This syntax also enables method chaining and constructor delegation (this(...)).
40
What are primary constructors in C# 12?
Correct Answer
Constructor parameters declared in the class header, available throughout the class body as captured members
Explanation
class Point(int x, int y) { public int X => x; } captures x and y for use in the class body, reducing boilerplate constructor code.
1
What is the difference between IEnumerable<T> and IQueryable<T>?
Correct Answer
IEnumerable executes queries in memory; IQueryable translates queries to SQL/provider-specific language for server-side execution
Explanation
IEnumerable LINQ operates on in-memory data. IQueryable (used by EF) builds expression trees sent to the database, avoiding pulling all data into memory.
2
What is a Task in C# and how does it differ from void async methods?
Correct Answer
Task-returning async methods can be awaited and observed for exceptions; async void is fire-and-forget and unobservable
Explanation
async void exceptions crash the application unhandled. async Task is awaitable and its exceptions can be caught. async void is only acceptable for event handlers.
3
What is the IEnumerable<T> interface and yield return?
Correct Answer
IEnumerable<T> supports forward-only iteration. yield return creates an iterator method that lazily generates values one at a time
Explanation
Iterator methods using yield return produce values on-demand as the consumer iterates, enabling memory-efficient pipelines.
4
What is the difference between Func<T, TResult> and Action<T>?
Correct Answer
Func represents a method that returns a value; Action represents a method that returns void
Explanation
Func<int, string> takes an int and returns a string. Action<int> takes an int and returns void.
5
What is a record type in C# (C# 9+)?
Correct Answer
An immutable reference type with value-based equality and auto-generated toString, equals, and with-expression support
Explanation
record Person(string Name, int Age); auto-generates equality, deconstruction, and with-expressions: var older = person with { Age = 30 };.
6
What are nullable reference types in C# 8+?
Correct Answer
A compiler feature that treats reference types as non-nullable by default, requiring ? to opt into null
Explanation
Enabling <Nullable>enable</Nullable> makes string non-nullable. string? allows null. The compiler warns on potential NullReferenceExceptions.
7
What is pattern matching in C#?
Correct Answer
A language feature for testing expressions against patterns (type, constant, property) in switch and if statements
Explanation
if (obj is int n) { } or switch(shape) { case Circle c when c.Radius > 5: } are patterns. C# 8-12 continuously expanded pattern types.
8
What are extension methods in C#?
Correct Answer
Static methods in a static class that add methods to existing types without modifying them, called as if they were instance methods
Explanation
static int WordCount(this string s) => s.Split().Length; allows "Hello World".WordCount(). LINQ methods are extension methods on IEnumerable.
9
What is the difference between ref and out parameters?
Correct Answer
ref passes by reference and requires initialization before passing; out passes by reference and must be assigned in the method
Explanation
ref int x requires x to be assigned before the call. out int y does not (the method must assign it). int.TryParse uses out.
10
What is an indexer in C#?
Correct Answer
A class member allowing objects to be indexed like arrays using [] syntax
Explanation
public T this[int i] { get => items[i]; set => items[i] = value; } allows myObj[0] syntax on custom classes.
11
What is covariance and contravariance in C# generics?
Correct Answer
Covariance (out) allows using a more derived type; contravariance (in) allows using a less derived type in generic parameter position
Explanation
IEnumerable<out T> is covariant — IEnumerable<Dog> can be assigned to IEnumerable<Animal>. IComparer<in T> is contravariant.
12
What is a CancellationToken?
Correct Answer
A mechanism to cooperatively cancel async or long-running operations
Explanation
Pass CancellationToken to async methods. Check token.IsCancellationRequested or call token.ThrowIfCancellationRequested() at safe points.
13
What is the difference between lock and Monitor in C#?
Correct Answer
lock is syntactic sugar for Monitor.Enter/Monitor.Exit, providing a simpler way to synchronize access
Explanation
lock (obj) { } compiles to Monitor.Enter(obj, ref lockTaken); try { ... } finally { Monitor.Exit(obj); }. Monitor offers TryEnter with timeout.
14
What is an attribute in C#?
Correct Answer
Metadata annotations applied to types, methods, or parameters, readable via Reflection
Explanation
[Obsolete("Use NewMethod instead")] and [Required] are attributes. Frameworks use Reflection to read them at runtime for validation, routing, etc.
15
What is LINQ's deferred execution?
Correct Answer
LINQ query expressions are not executed until the result is iterated (foreach, ToList, First, etc.)
Explanation
var q = list.Where(x => x > 5); doesn't execute until iterated. This allows composing queries lazily. ToList() forces immediate execution.
16
What is the Span<T> type in C#?
Correct Answer
A stack-only ref struct providing a view over a contiguous memory region without allocation
Explanation
Span<T> slices arrays, strings, or stack memory with zero allocation, enabling high-performance parsing and processing without copying.
17
What does ConfigureAwait(false) do?
Correct Answer
Resumes the continuation on any thread pool thread rather than capturing and returning to the original synchronization context
Explanation
Without ConfigureAwait(false), await tries to resume on the original context (e.g., UI thread). Library code should use ConfigureAwait(false) to avoid deadlocks.
18
What is the difference between ValueTask and Task?
Correct Answer
ValueTask is a struct that avoids heap allocation when a result is available synchronously, unlike Task which always allocates
Explanation
ValueTask<T> avoids Task allocation when the operation completes synchronously (common in cache-hit paths). Task is safe to await multiple times; ValueTask is not.
19
What is a source generator in C#?
Correct Answer
A Roslyn API that generates additional C# source code during compilation based on existing code analysis
Explanation
Source generators (IIncrementalGenerator) run during compilation and add generated files to the project. Used by System.Text.Json, regex source gen, and DI containers.
20
What is the init accessor in C# 9?
Correct Answer
A property accessor that allows setting only during object initialization, making the property effectively immutable afterward
Explanation
public string Name { get; init; } can be set in object initializers (new Person { Name = "Alice" }) but not after the object is constructed.
21
What is an implicit operator in C#?
Correct Answer
A user-defined conversion that occurs silently without explicit cast syntax
Explanation
public static implicit operator string(MyType t) allows string s = myTypeValue; automatically. Explicit operators require (string)myTypeValue.
22
What is the Decorator pattern in C# and when would you use it?
Correct Answer
Wrapping an object in another implementing the same interface to add behavior without modifying the original class
Explanation
class LoggingRepository : IRepository { IRepository _inner; ... } wraps an IRepository and adds logging. Enables Open/Closed Principle compliance.
23
What is the purpose of IAsyncEnumerable<T>?
Correct Answer
An interface for asynchronous streams — data produced and consumed asynchronously using await foreach
Explanation
await foreach (var item in GetDataAsync()) processes items as they become available without buffering all results. Useful for database cursors, API pagination.
24
What is the difference between string and StringBuilder for performance?
Correct Answer
string is immutable; repeated concatenation creates many objects. StringBuilder avoids this by mutating an internal buffer
Explanation
string s = a + b + c creates two intermediate strings. var sb = new StringBuilder(); sb.Append(a); sb.Append(b); sb.Append(c); allocates one buffer.
25
What is a Lazy<T> in C#?
Correct Answer
A thread-safe wrapper that initializes its value on first access using a factory function
Explanation
Lazy<HeavyObject> obj = new(() => new HeavyObject()); obj.Value triggers initialization on first access. Thread-safe by default.
26
What is the using declaration (C# 8)?
Correct Answer
A declaration that disposes the resource at the end of the enclosing scope without a block
Explanation
using var conn = GetConnection(); disposes conn at end of the method instead of requiring a using { } block, reducing indentation.
27
What is object pooling in C# and when should you use it?
Correct Answer
Reusing expensive objects (connections, buffers) from a pool instead of creating and destroying them, reducing GC pressure
Explanation
ArrayPool<T>.Shared.Rent(size) and Return() reuse arrays. ObjectPool<T> (Microsoft.Extensions) generalizes this. Crucial for high-throughput scenarios.
28
What is the IProgress<T> interface?
Correct Answer
A standard way to report progress from a long-running operation back to the calling context (typically UI thread)
Explanation
void Process(IProgress<int> progress) { progress.Report(50); } and new Progress<int>(pct => UpdateUI(pct)) in the caller.
29
What is the difference between Func<T, TResult> and Expression<Func<T, TResult>>?
Correct Answer
Func is a compiled delegate; Expression wraps the lambda as a data structure that can be inspected and translated (e.g., to SQL by EF Core)
Explanation
Expression<Func<User, bool>> pred = u => u.Age > 18 creates a tree. pred.Compile() gets a runnable Func. EF Core translates the tree to WHERE Age > 18 SQL.
30
What are channels in .NET System.Threading.Channels?
Correct Answer
A high-performance, async producer-consumer channel for safely passing data between tasks
Explanation
Channel<T>.CreateBounded(100) creates a bounded async queue. await writer.WriteAsync(item) and await reader.ReadAsync() are async producer/consumer operations.
31
What is the Action<> and Func<> delegate shorthand for?
Correct Answer
Built-in delegates replacing custom delegate declarations for common patterns
Explanation
Action<int, string> replaces delegate void MyDel(int a, string b). Func<int, string, bool> replaces delegate bool MyFunc(int a, string b). Reduces delegate boilerplate.
32
What are default interface methods in C# 8?
Correct Answer
Interface methods with implementations, allowing new members to be added to an interface without breaking existing implementors
Explanation
interface ILogger { void Log(string msg); void LogError(string msg) => Log($"ERROR: {msg}"); } — implementors get LogError for free but can override it.
33
What is top-level statements in .NET 6+?
Correct Answer
A C# 9 feature allowing program entry point code without explicit Main() method or class, reducing boilerplate
Explanation
A file with just Console.WriteLine("Hello"); is a valid .NET 6 program — the compiler generates the Program class and Main() method implicitly.
34
What is the Roslyn API?
Correct Answer
The open-source .NET compiler platform providing APIs to analyze, generate, and modify C# and VB.NET code
Explanation
Roslyn exposes the compiler as an API. Source generators, analyzers, and code fixers use Roslyn's SyntaxTree, SemanticModel, and compilation APIs.
35
What is the File-Scoped Namespace in C# 10?
Correct Answer
A declaration syntax (namespace Foo;) removing one level of indentation for the entire file
Explanation
namespace MyApp.Models; at the top of a file removes the { } block, reducing indentation for all types in the file.
36
What is global using in C# 10?
Correct Answer
global using System; adds the using directive to every file in the project without repeating it
Explanation
.NET 6+ project templates add global using System; and others automatically. You can define them in a GlobalUsings.cs file for the project.
37
What is collection expressions in C# 12?
Correct Answer
A syntax using [ ] to create any collection type with optional spread (..) operator
Explanation
int[] a = [1, 2, 3]; List<int> b = [4, 5]; int[] c = [..a, ..b]; Collection expressions work for arrays, spans, and any type with a CollectionBuilder attribute.
38
What is the frozen collections in .NET 8?
Correct Answer
Read-only optimized collections (FrozenDictionary, FrozenSet) with faster lookup at the cost of slower construction
Explanation
FrozenDictionary<string, int> is built once from an IEnumerable and optimized for fast reads. Ideal for configuration data loaded at startup.
39
What is the difference between IEnumerable and IReadOnlyCollection in C#?
Correct Answer
IEnumerable is forward-only lazy; IReadOnlyCollection adds Count and Contains, implying the collection is fully materialized
Explanation
Prefer IReadOnlyCollection<T> in APIs when callers need Count without materializing. Use IEnumerable<T> only when lazy evaluation is intentional.
40
What is the purpose of the params keyword in C#?
Correct Answer
Allows a method to accept a variable number of arguments of the same type without requiring an array literal
Explanation
void Log(string msg, params object[] args) can be called as Log("x", 1, "y", 2). Internally the args are an array.
1
What is the .NET runtime's GC generational model?
Correct Answer
Objects are placed in generation 0, 1, or 2. Short-lived objects stay in gen 0; survivors are promoted. Gen 2 is collected least frequently
Explanation
Gen 0 collections are fast and frequent. Objects that survive are promoted to Gen 1, then Gen 2. Gen 2 (full GC) is expensive and should be infrequent.
2
What is the difference between managed and unmanaged resources in .NET?
Correct Answer
Managed resources are tracked by the GC; unmanaged resources (files, sockets, native memory) must be released manually via IDisposable
Explanation
The GC handles managed memory automatically. Unmanaged resources (OS handles, COM objects) need Dispose() or finalizers to be released.
3
What is the Dispose pattern and when should you implement a finalizer?
Correct Answer
Only add a finalizer if the class directly owns unmanaged resources (handles). Implement the full Dispose(bool disposing) pattern to handle both Dispose() and GC finalization
Explanation
Finalizers (~MyClass) are a safety net for unmanaged resources. They delay GC and should be suppressed via GC.SuppressFinalize(this) when Dispose() is called.
4
What is IL (Intermediate Language) and how does the JIT compile it?
Correct Answer
C# compiles to platform-neutral IL. The JIT compiles IL to native machine code on first method call, caching the result
Explanation
IL enables cross-language and cross-platform portability. The JIT (or AOT via NativeAOT) compiles IL to native code. Methods are JIT-compiled on first invocation.
5
What is the difference between SemaphoreSlim and Semaphore?
Correct Answer
SemaphoreSlim is a lightweight intra-process semaphore with async support; Semaphore is a kernel primitive supporting cross-process sync
Explanation
SemaphoreSlim.WaitAsync() is async-compatible, crucial for async code. Semaphore wraps a Win32 kernel object and supports cross-process synchronization.
6
What is the Expression<T> type?
Correct Answer
A representation of a lambda as a data structure (expression tree) that can be analyzed, translated, or compiled at runtime
Explanation
Expression<Func<User, bool>> expr = u => u.Age > 18; creates an expression tree. EF Core translates it to SQL. Call .Compile() to get a runnable Func.
7
What is the purpose of the unsafe keyword in C#?
Correct Answer
Enables code that bypasses type safety for direct memory access using pointers
Explanation
unsafe blocks allow pointer arithmetic (int* p = &x). Requires /unsafe compile flag. Used for interop, performance-critical code, and Span<T> internals.
8
What is covariant return types in C# (C# 9)?
Correct Answer
An override can return a more derived type than the base method's return type
Explanation
class Animal { virtual Animal Create() ... } class Dog : Animal { override Dog Create() ... } is valid in C# 9 — the override returns a more specific type.
9
What is the difference between Thread.Sleep and Task.Delay?
Correct Answer
Thread.Sleep blocks the thread; Task.Delay is async and releases the thread during the wait
Explanation
Thread.Sleep(1000) blocks the OS thread for 1 second. await Task.Delay(1000) suspends the async method, returning the thread to the pool during the wait.
10
What is a ref struct in C# and what restrictions apply?
Correct Answer
A struct that can only exist on the stack or in registers, cannot be boxed, stored in fields of regular types, or captured by lambdas
Explanation
ref structs (Span<T>, ReadOnlySpan<T>) cannot be stored on the heap. This enables the runtime to guarantee their lifetime without GC tracking.
11
What is .NET's NativeAOT compilation?
Correct Answer
Ahead-of-time compilation to a native self-contained executable with no JIT and reduced startup time, at the cost of reflection limitations
Explanation
NativeAOT compiles all managed code to native ahead-of-time. The result is a self-contained native binary with fast startup. Reflection and dynamic code generation are constrained.
12
What is the .NET runtime's tiered compilation?
Correct Answer
Running new methods with quick-JIT first, then re-JIT-compiling hot methods with full optimizations after they are called frequently
Explanation
Tiered compilation (enabled by default) starts with Tier 0 (quick JIT) for fast startup, then promotes hot methods to Tier 1 (full optimized JIT) improving peak throughput.
13
What is the .NET Runtime Performance Improvement approach with Spans?
Correct Answer
Span<T> and stackalloc enable processing data without heap allocations, eliminating GC pressure in tight loops
Explanation
int[] result = new int[n] on hot paths allocates GC-tracked memory. stackalloc + Span<int> puts the array on the stack — zero GC impact for small, scoped buffers.
14
What is the C# abstract record and how does it interact with pattern matching?
Correct Answer
Abstract records provide a base for record hierarchies; switch expressions can use positional patterns on derived records for exhaustive case handling
Explanation
abstract record Shape; record Circle(double R) : Shape; switch(shape) { case Circle(var r): ... } uses positional deconstruction pattern matching on the record hierarchy.
15
What is the Dispose Pattern and GC.SuppressFinalize interaction?
Correct Answer
GC.SuppressFinalize(this) in Dispose() removes the object from the finalization queue so the GC doesn't spend extra time re-visiting it
Explanation
Adding a finalizer puts the object on the finalization queue (extra GC cycle). GC.SuppressFinalize() after explicit Dispose() avoids this overhead.
16
What is the .NET System.Text.Json source generation?
Correct Answer
A source generator that produces optimized serialization code at compile time for AOT compatibility and improved performance
Explanation
[JsonSerializable(typeof(User))] attribute on a JsonSerializerContext generates optimal serializers. Eliminates reflection, enabling NativeAOT compatibility.
17
What is the .NET green thread (Task) versus OS thread performance model?
Correct Answer
Tasks use the thread pool: creating a Task costs microseconds; creating an OS thread costs milliseconds and ~1MB stack. Millions of Tasks can exist; thousands of threads struggle
Explanation
Thread pool reuse amortizes thread creation overhead. async/await enables millions of concurrent I/O operations with just a handful of OS threads.
18
What is MVVM pattern and how does it relate to C# data binding?
Correct Answer
Model-View-ViewModel: a design pattern where ViewModel exposes data via INotifyPropertyChanged for two-way UI binding
Explanation
INotifyPropertyChanged.PropertyChanged triggers UI updates. Commands (ICommand) handle interactions. MVVM enables testable UI logic without direct UI references.
19
What is the .NET Memory Model and how does it differ from the JMM?
Correct Answer
The .NET Memory Model uses volatile reads/writes and Interlocked for synchronization. volatile in C# is weaker than Java — it does not guarantee ordering of other memory operations
Explanation
C# volatile prevents read/write reordering for that specific variable but doesn't have Java's full happens-before guarantee for surrounding operations. Use Thread.MemoryBarrier() or Interlocked for stronger guarantees.
20
What is the difference between Debug and Release configurations in .NET?
Correct Answer
Debug disables optimizations and includes debug symbols; Release enables full JIT/AOT optimizations, eliminates debug-only code, and strips symbols
Explanation
Debug preserves debuggable stack frames and disables inlining. Release enables inlining, loop unrolling, dead code elimination via JIT. Can be 2-10x faster.