Top C# Interview Questions

Curated C# interview questions and answers across difficulty levels.

Last updated:

C# Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of C# interview questions and answers. This page contains expertly curated interview questions covering all aspects of C#, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our C# interview questions are designed to help you:

  • Understand core concepts and best practices in C#
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next C# interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic C# concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

173 questions
Q1:

What are value types and reference types?

Entry

Answer

Value types: store data directly (int, bool, double, struct). Reference types: store a reference to memory (class, interface, array, string).
Q2:

What is boxing and unboxing?

Entry

Answer

Boxing: value type → converted to object (heap)Unboxing: object → converted back to value type


int x = 10;object obj = x;        // boxingint y = (int)obj;      // unboxing

Q3:

What is garbage collection?

Entry

Answer

Automatic memory cleanup.

GC removes unused objects from the heap and prevents memory leaks.

Q4:

What is an interface?

Entry

Answer

A contract that defines method signatures without implementation.

A class must implement all the interface members.


interface IAnimal { void Speak(); }


Q5:

What is abstraction?

Entry

Answer

Hiding internal implementation and exposing only essential features.

Achieved using interfaces or abstract classes.

Q6:

What is encapsulation?

Entry

Answer

Protecting data through access modifiers and properties.

private int age;

public int Age { get; set; }


Q7:

What are access modifiers in C#?

Entry

Answer

publicprivateprotectedinternalprotected internalprivate protected

Control visibility of classes and members.

Q8:

What is polymorphism?

Entry

Answer

Same method name behaves differently based on object type.
Two types:

  • Compile-time (method overloading)
  • Runtime (method overriding using override )

Q9:

What is method overriding?

Entry

Answer

Child class provides new implementation for a parent class method.


public virtual void Speak() { }

public override void Speak() { }


Q10:

What is a constructor?

Entry

Answer

A special method executed when an object is created.

public Student() { }


Q11:

What is a static constructor?

Entry

Answer

Runs only once per type — initializes static members.

static Student() { }


Q12:

What is an exception?

Entry

Answer

An error that occurs during runtime.

Handled using try…catch.

try { } 

catch(Exception ex) { }


Q13:

What is the difference between == and Equals()?

Entry

Answer

  • == → compares values for value types; references for reference types

    • Equals() → can be overridden for value comparison in reference types (e.g., string)

  • Q14:

    What is C#?

    Junior

    Answer

    C# is a type-safe, object-oriented programming language developed by Microsoft for building modern applications on .NET. It supports OOP, strong typing, and a rich standard library.
    Q15:

    What is the .NET Framework / .NET Runtime?

    Junior

    Answer

    It’s a runtime environment that loads C# code, manages memory, handles garbage collection, and provides built-in libraries for I/O, networking, collections, threading, etc.
    Q16:

    What is a namespace?

    Junior

    Answer

    A namespace is a logical container used to group related classes, interfaces, and enums for better organization and to avoid name collisions.
    Q17:

    What is a nullable type in C#?

    Junior

    Answer

    A nullable type allows a value type to also store a null value. It is useful when a variable may or may not have a valid data value.

    Q18:

    What is the difference between Array and List?

    Junior

    Answer

    First: An array has a fixed size.
    Second: A List can grow or shrink dynamically.
    Arrays are faster for fixed collections, Lists are flexible and easier to use.

    Q19:

    What is the purpose of the var keyword?

    Junior

    Answer

    var allows the compiler to infer the type of a variable automatically.
    The actual type is determined at compile-time, not runtime.
    Q20:

    What is an enum?

    Junior

    Answer

    An enum is a special value type that represents a set of named constant values.

    It improves readability when working with predefined options, categories, or states.

    Q21:

    What are properties in C#?

    Junior

    Answer

    Properties provide controlled access to internal fields of a class.

    They allow getting or setting values while applying validation or logic if needed.

    Q22:

    What is an indexer?

    Junior

    Answer

    An indexer allows an object to be accessed like an array.

    It enables retrieving values using an index without exposing internal data structures.

    Q23:

    What is a delegate?

    Junior

    Answer

    A delegate is a type that holds a reference to a method.

    It enables methods to be treated as objects and passed as parameters.

    Q24:

    What is an event in C#?

    Junior

    Answer

    An event allows an object to notify other objects when something happens.

    Events follow the publisher–subscriber pattern and are based on delegates.

    Q25:

    What is the difference between break and continue?

    Junior

    Answer

    break: Immediately exits the loop.

    continue: Skips the current iteration and moves to the next one.

    Q26:

    What is the difference between ref and out keywords?

    Junior

    Answer

    ref: The variable must be initialized before passing.

    out: Initialization is not required before passing, but must be assigned inside the method.

    Q27:

    What is a sealed class?

    Junior

    Answer

    A sealed class cannot be inherited.

    It is used to prevent further extension of a class.

    Q28:

    What is a partial class?

    Junior

    Answer

    A partial class allows a class definition to be split across multiple files.

    Commonly used in large projects and generated code.

    Q29:

    What is the purpose of the using statement?

    Junior

    Answer

    The using statement ensures that disposable resources are released automatically when the block ends.

    Q30:

    What is a thread in C#?

    Junior

    Answer

    A thread is the smallest unit of execution.

    It allows multiple tasks to run concurrently.

    Q31:

    What is multithreading?

    Junior

    Answer

    Multithreading enables a program to perform multiple operations simultaneously using multiple threads.

    Q32:

    What is the lock keyword used for?

    Junior

    Answer

    The lock keyword prevents multiple threads from accessing a shared resource at the same time.

    It ensures thread safety.

    Q33:

    What is Just-In-Time (JIT) compilation?

    Junior

    Answer

    JIT compiler converts IL code into machine code at runtime.

    It optimizes execution for the system's hardware and OS.

    Q34:

    What is the difference between is and as operators?

    Junior

    Answer

    is: Checks whether an object is of a specific type.

    as: Attempts conversion and returns null if conversion fails.

    Q35:

    What is the base keyword?

    Junior

    Answer

    The base keyword is used in a derived class to access members of the parent class.

    It is useful for calling parent constructors or overridden methods.

    Q36:

    What is the purpose of the readonly struct?

    Junior

    Answer

    A readonly struct ensures that all fields remain immutable.

    It improves performance by avoiding unnecessary copies.

    Q37:

    What is the difference between a field and a property?

    Junior

    Answer

    Field: Stores data directly inside a class.

    Property: Provides controlled access to data using getters and setters.

    Q38:

    What is an anonymous type in C#?

    Junior

    Answer

    An anonymous type is an object created without defining a class.

    The compiler generates a temporary type with read-only properties.

    Q39:

    What is the difference between IEnumerable and IEnumerator?

    Junior

    Answer

    IEnumerable: Represents a collection that can be iterated.

    IEnumerator: Performs step-by-step iteration over the collection.

    Q40:

    What is the difference between IEnumerable and IQueryable?

    Junior

    Answer

    IEnumerable: Executes queries in memory (LINQ to Objects).

    IQueryable: Builds expression trees and allows external systems like databases to execute queries.

    Q41:

    What is the purpose of extension methods?

    Junior

    Answer

    Extension methods allow adding new functionality to existing types without modifying their source code or creating derived classes.

    Q42:

    What is a static class?

    Junior

    Answer

    A static class cannot be instantiated.

    It contains only static members and is commonly used for utility functions.

    Q43:

    What is the base class for all types in C#?

    Junior

    Answer

    The root class for all .NET types is System.Object.

    It provides behaviors like equality, hashing, and type information.

    Q44:

    What is a destructor in C#?

    Junior

    Answer

    A destructor is a method called when an object is being cleaned up.

    It is rarely used because memory is managed by the garbage collector.

    Q45:

    What is method hiding in C#?

    Junior

    Answer

    Method hiding occurs when a derived class defines a method with the same name as the parent class but does not override it.

    The new method hides the parent method when accessed via the derived type.

    Q46:

    What is the difference between early binding and late binding?

    Junior

    Answer

    Early binding: Type information is known at compile time.

    Late binding: Type information is resolved at runtime.

    Q47:

    What is the yield keyword used for?

    Junior

    Answer

    The yield keyword simplifies iterator creation.

    It returns values one at a time without creating a separate collection.

    Q48:

    What is a generic type?

    Junior

    Answer

    A generic type allows a class or method to work with multiple data types while maintaining type safety and performance.

    Q49:

    What is covariance and contravariance?

    Junior

    Answer

    Covariance: Allows using a more derived type than originally specified.

    Contravariance: Allows using a more base type than originally specified.

    Q50:

    What is dependency injection in C#?

    Junior

    Answer

    Dependency Injection (DI) provides required objects from outside rather than creating them internally.

    It improves modularity, testability, and maintainability.

    Q51:

    What is the difference between Task and Thread?

    Junior

    Answer

    Thread: A physical execution unit.

    Task: A higher-level abstraction optimized for asynchronous operations.

    Q52:

    What is async and await used for?

    Junior

    Answer

    async marks a method as asynchronous.

    await pauses execution until the awaited task completes without blocking the thread.

    Q53:

    What is a race condition?

    Junior

    Answer

    A race condition happens when multiple threads access or modify shared data simultaneously, causing unpredictable behavior.

    Q54:

    What is a deadlock?

    Junior

    Answer

    Deadlock occurs when multiple threads wait for each other's resources and none of them can continue.

    Q55:

    What is the difference between stack and heap memory?

    Junior

    Answer

    Stack: Stores value types and method call information.

    Heap: Stores reference types and dynamically allocated objects.

    Q56:

    What is an attribute in C#?

    Junior

    Answer

    An attribute is metadata applied to program elements like classes, methods, or properties.

    It helps frameworks control behavior at compile time or runtime.

    Q57:

    What is the purpose of the volatile keyword?

    Mid

    Answer

    The volatile keyword tells the compiler that a variable may be modified by multiple threads.

    It prevents certain optimizations and ensures every read returns the most recent value.

    Q58:

    What is the difference between abstract class and interface?

    Mid

    Answer

    Abstract class: Can contain both implementation and abstraction.

    Interface: Defines only the contract with no implementation (in traditional C#).

    A class can inherit one abstract class but implement multiple interfaces.

    Q59:

    What is a virtual method?

    Mid

    Answer

    A virtual method allows derived classes to override behavior and provide their own implementation.

    Q60:

    What is the difference between Finalize and Dispose?

    Mid

    Answer

    Finalize: Called by the garbage collector.

    Dispose: Invoked manually to release unmanaged resources deterministically.

    Q61:

    What is the difference between shallow copy and deep copy?

    Mid

    Answer

    Shallow copy: Copies only references of reference-type fields.

    Deep copy: Creates a fully independent copy of the entire object graph.

    Q62:

    What is reflection in C#?

    Mid

    Answer

    Reflection allows inspecting metadata and interacting with types, methods, and properties at runtime.

    Q63:

    What is dynamic type in C#?

    Mid

    Answer

    The dynamic type skips compile-time checking and resolves member access at runtime.

    Q64:

    What is the difference between public API and internal API in C#?

    Mid

    Answer

    Public API: Accessible from any assembly.

    Internal API: Accessible only within the same assembly.

    Q65:

    What is an assembly in .NET?

    Mid

    Answer

    An assembly is a deployable unit containing compiled code, metadata, and resources.

    It is typically a DLL or EXE file.

    Q66:

    What is the purpose of the params keyword?

    Mid

    Answer

    The params keyword allows passing a variable number of arguments to a method without explicitly creating an array.

    Q67:

    What is an explicit interface implementation?

    Mid

    Answer

    Explicit interface implementation allows a class to implement multiple interface methods with the same name without conflict.

    The implemented method is accessible only through an interface reference.

    Q68:

    What is the difference between readonly field and property?

    Mid

    Answer

    Readonly field: Assigned only during declaration or constructor.

    Property: Encapsulates logic and allows controlled read/write through getters and setters.

    Q69:

    What is an unsafe context in C#?

    Mid

    Answer

    Unsafe context enables pointer operations and direct memory access for performance-critical scenarios.

    Q70:

    What are custom exceptions?

    Mid

    Answer

    Custom exceptions are user-defined exception classes representing application-specific errors.

    Q71:

    What is the purpose of the nameof operator?

    Mid

    Answer

    The nameof operator returns the string name of variables, properties, or methods.

    It eliminates magic strings and improves refactoring safety.

    Q72:

    What is method shadowing?

    Mid

    Answer

    Method shadowing occurs when a derived class hides a method from the base class using the new keyword.

    Q73:

    What is the difference between synchronous and asynchronous execution?

    Mid

    Answer

    Synchronous: Blocks the calling thread until the operation completes.

    Asynchronous: Continues execution without blocking, offering better scalability and responsiveness.

    Q74:

    What is a memory leak in .NET?

    Mid

    Answer

    A memory leak occurs when unused objects remain referenced, preventing garbage collection and increasing memory usage.

    Q75:

    What is the purpose of StringBuilder?

    Mid

    Answer

    StringBuilder efficiently manages dynamic string modifications without creating multiple intermediate immutable strings.

    Q76:

    What is the difference between equality operator and reference equality?

    Mid

    Answer

    Equality operator: Checks logical equality when overridden.

    Reference equality: Checks if two references point to the same object instance.

    Q77:

    What is the difference between value-type semantics and reference-type semantics in C#?

    Mid

    Answer

    Value types store their actual data directly on the stack (or inline within other objects). Assigning one value type to another copies all data.

    Reference types store references to objects on the heap. Assigning one reference variable to another makes both point to the same object.

    This difference impacts memory layout, performance, assignment behavior, parameter passing, and garbage collection.

    Q78:

    What is boxing and unboxing in C#? Why does it affect performance?

    Mid

    Answer

    Boxing converts a value type into an object by wrapping it inside a heap-allocated reference type.

    Unboxing extracts the value type back from the object.

    Boxing and unboxing are slow due to heap allocation, GC pressure, and runtime type-checking.

    Q79:

    What is the purpose of the IDisposable interface? When should you implement it?

    Mid

    Answer

    IDisposable defines a contract for releasing unmanaged resources such as file handles, sockets, and database connections.

    Implement IDisposable when your class owns unmanaged resources that the garbage collector cannot free automatically.

    Q80:

    What are generics in C#, and why are they important?

    Mid

    Answer

    Generics enable type-safe classes and methods that work with any data type.

    They eliminate casting, reduce runtime errors, prevent boxing, and improve performance.

    Q81:

    What is the difference between const and readonly?

    Mid

    Answer

    const: Compile-time constant; must be assigned at declaration.

    readonly: Runtime constant; can be assigned at declaration or inside a constructor.

    Readonly avoids versioning issues because its value is not embedded into IL.

    Q82:

    What is the difference between overloading and overriding in C#?

    Mid

    Answer

    Overloading: Same method name, different parameters; resolved at compile time.

    Overriding: Derived class redefines base class virtual methods; resolved at runtime.

    Q83:

    What is the purpose of the GC (Garbage Collector) in .NET? How does it work?

    Mid

    Answer

    The Garbage Collector (GC) frees unused heap objects automatically.

    It uses generations (Gen0, Gen1, Gen2) to optimize collection of short-lived and long-lived objects.

    The GC pauses execution, removes unreachable objects, and compacts memory.

    Q84:

    What is the difference between synchronous and asynchronous execution in C#?

    Mid

    Answer

    Synchronous: Blocks the calling thread until completion.

    Asynchronous: Frees the thread and allows other operations to run concurrently.

    Async-await uses Tasks and compiler-generated state machines.

    Q85:

    What are thread-safe operations, and why are they important?

    Mid

    Answer

    Thread-safe operations ensure consistent behavior when accessed concurrently by multiple threads.

    They prevent race conditions, deadlocks, inconsistent states, and crashes.

    Q86:

    What is immutability? Why is it recommended in multi-threaded scenarios?

    Mid

    Answer

    Immutability means an object's state cannot change after creation.

    It avoids the need for locks and prevents corruption in multi-threaded environments.

    Q87:

    What is the difference between static constructor and instance constructor?

    Mid

    Answer

    Static constructor: Initializes static members once per type.

    Instance constructor: Initializes object instances and runs per object.

    Q88:

    What is a delegate chain (multicast delegate)?

    Mid

    Answer

    A delegate chain is a list of methods attached to a single delegate.

    Invoking the delegate executes all attached methods in sequence.

    Q89:

    What is an event handler in C#, technically?

    Mid

    Answer

    An event handler is a delegate following the .NET event pattern.

    Events encapsulate delegates and restrict invocation to the declaring class.

    Q90:

    What is reflection emit?

    Mid

    Answer

    Reflection Emit enables runtime creation of types, methods, and IL.

    Used in ORMs, serializers, proxies, and dynamic frameworks.

    Q91:

    What is the purpose of strong naming assemblies?

    Mid

    Answer

    Strong naming uses a cryptographic key pair to sign assemblies.

    It ensures authenticity, prevents tampering, and enables GAC deployment.

    Q92:

    What is method binding?

    Mid

    Answer

    Method binding connects method calls to implementations.

    Early binding = compile time; late binding = runtime.

    Q93:

    What are attributes in C#, and how do they work?

    Mid

    Answer

    Attributes add metadata to program elements.

    Frameworks read attributes to enforce policies, control behavior, or generate code.

    Q94:

    What is the difference between a struct and a class in C#?

    Mid

    Answer

    Struct: Value type, stack-allocated, lightweight.

    Class: Reference type, heap-allocated, supports inheritance and advanced OOP.

    Q95:

    What is tail recursion?

    Mid

    Answer

    Tail recursion occurs when the final operation of a method is a recursive call.

    Allows optimization of stack usage and prevents stack overflow.

    Q96:

    What are anonymous methods?

    Mid

    Answer

    Anonymous methods allow defining inline method bodies.

    They support closures and are often used in event handling.

    Q97:

    What is the difference between class-level variables and method-level variables?

    Senior

    Answer

    Class-level variables belong to the object and persist for its lifetime. They maintain state across method calls and can be accessed by all methods inside the class.

    Method-level variables exist only within the method scope and are destroyed once the method finishes. They do not retain state across calls and are suited for temporary data.

    Q98:

    What is the significance of using interfaces in C#?

    Senior

    Answer

    Interfaces define a contract that implementing types must follow. They enable polymorphism, abstraction, dependency injection, and loose coupling.

    They also make unit testing easier by allowing mock implementations.

    Q99:

    What happens when you mark a class as sealed?

    Senior

    Answer

    A sealed class cannot be inherited. It prevents further extension and allows the compiler to optimize method calls.

    It is commonly used to avoid misuse or unintended inheritance.

    Q100:

    What is the difference between readonly and const fields?

    Senior

    Answer

    const: Compile-time constant; must be assigned at declaration and is implicitly static.

    readonly: Runtime constant; can be assigned at declaration or inside the constructor and allows flexibility when values depend on runtime state.

    Q101:

    How does boxing affect application performance?

    Senior

    Answer

    Boxing converts a value type into an object by allocating memory on the heap.

    Frequent boxing/unboxing causes extra allocations, garbage collection pressure, and type-check overhead, which degrade performance.

    Q102:

    What are extension methods, and when should you avoid them?

    Senior

    Answer

    Extension methods add functionality to existing types without modifying them.

    You should avoid them when they reduce readability, create ambiguity, or introduce responsibilities that do not logically belong to the type.

    Q103:

    What is the purpose of the new keyword in method definitions?

    Senior

    Answer

    The new keyword hides an inherited member intentionally, preventing compiler warnings and signaling deliberate shadowing behavior.

    Q104:

    What are nullable value types?

    Senior

    Answer

    Nullable value types allow value types to store an additional null state, useful for representing missing or undefined data such as database fields.

    Q105:

    What is the difference between deep copy and shallow copy?

    Senior

    Answer

    Shallow copy copies only top-level values; reference fields still point to shared objects.

    Deep copy duplicates the full object graph, ensuring complete independence at the cost of extra memory and performance.

    Q106:

    What is the use of the base keyword?

    Senior

    Answer

    The base keyword accesses parent class members from derived classes.

    It is used to call parent constructors or access overridden members.

    Q107:

    Why are static constructors used?

    Senior

    Answer

    Static constructors initialize static fields and execute once before the type is first used.

    They provide thread-safe, automatic initialization without explicit synchronization.

    Q108:

    What is the difference between implicit and explicit type conversion?

    Senior

    Answer

    Implicit conversions occur automatically when safe.

    Explicit conversions require manual casting due to potential data loss.

    Q109:

    What are partial classes?

    Senior

    Answer

    Partial classes split a class across multiple files, useful for separating generated code from custom logic.

    Q110:

    What is the difference between pass-by-value and pass-by-reference?

    Senior

    Answer

    Pass-by-value: Copies the value; modifications do not affect the original.

    Pass-by-reference: Passes the memory reference; modifications affect the original variable.

    Q111:

    What is overloading resolution?

    Senior

    Answer

    Overloading resolution is the compiler’s process for selecting the appropriate method among overloaded options based on parameters, type conversions, and context.

    Q112:

    Why does C# support optional parameters?

    Senior

    Answer

    Optional parameters reduce method overloads, simplify API usage, and maintain backward compatibility by allowing default values.

    Q113:

    What is the purpose of the Dispose pattern?

    Senior

    Answer

    The Dispose pattern ensures deterministic cleanup of unmanaged resources such as file handles and database connections.

    Q114:

    What is a destructor, and when does it run?

    Senior

    Answer

    Destructors execute when the garbage collector decides to free an object.

    They cannot be called manually and should be used only as a final safety mechanism.

    Q115:

    What is the purpose of strong typing in C#?

    Senior

    Answer

    Strong typing ensures variables are used only in compatible ways, preventing runtime type errors and enabling better compiler optimization.

    Q116:

    What is the Common Language Runtime (CLR), and why is it essential for C#?

    Expert

    Answer

    The CLR is the execution engine for .NET applications. It manages memory, performs JIT compilation, enforces type safety, handles exceptions, and manages garbage collection.

    It abstracts low-level memory management and provides a secure, consistent runtime environment, enabling cross-language interoperability and automatic memory management.

    Q117:

    How does the JIT compiler improve runtime performance in C#?

    Expert

    Answer

    The JIT compiler converts IL to machine code just before execution. It applies hardware-specific optimizations such as inlining, dead-code elimination, and CPU-tuned instruction generation.

    It may recompile methods dynamically based on runtime execution patterns, making performance adaptive.

    Q118:

    Why is C# considered a type-safe language?

    Expert

    Answer

    C# enforces strict type-checking, prevents unsafe casts, limits pointer operations, and ensures invalid operations are caught at compile time or enforced by the CLR.

    This eliminates memory corruption, improves security, and reduces runtime crashes.

    Q119:

    What is the difference between managed and unmanaged resources?

    Expert

    Answer

    Managed resources are controlled by the CLR (objects, arrays, strings), while unmanaged resources (file handles, sockets, DB connections) must be released manually via IDisposable.

    Failure to release unmanaged resources leads to leaks and OS-level exhaustion.

    Q120:

    Why does C# support nullable reference types, and what problem do they solve?

    Expert

    Answer

    Nullable reference types prevent null reference exceptions by enforcing compiler analysis and warnings for unsafe null operations.

    Q121:

    What is the significance of the volatile keyword?

    Expert

    Answer

    volatile ensures read/write operations always use the most current value and prevents CPU/compiler reordering.

    It is essential for correctness in low-level, lock-free synchronization.

    Q122:

    What is the difference between process memory and managed heap memory?

    Expert

    Answer

    Process memory includes stack, heap, DLL modules, native allocations, and OS buffers.

    Managed heap is only the CLR-controlled memory region used for .NET objects and garbage collection.

    Q123:

    How does string immutability help performance and safety?

    Expert

    Answer

    String immutability enables thread safety, prevents accidental mutation, and supports optimizations like interning.

    Q124:

    What is the role of metadata in .NET assemblies?

    Expert

    Answer

    Metadata contains structured information about types, members, attributes, and versioning.

    It powers reflection, type loading, serialization, security, and tooling support.

    Q125:

    Why is boxing considered an expensive operation?

    Expert

    Answer

    Boxing allocates heap memory, copies value types into objects, and causes GC overhead.

    Unboxing additionally requires type checking, making both operations costly.

    Q126:

    What is the purpose of the weak reference concept?

    Expert

    Answer

    Weak references allow referencing an object without preventing GC from collecting it.

    They are used in caching and memory-sensitive scenarios.

    Q127:

    What is reflection, and what are its risks?

    Expert

    Answer

    Reflection enables runtime inspection and invocation of types but is slower, bypasses compile-time type checks, exposes internals, and increases security risks.

    Q128:

    How does garbage collection deal with circular references?

    Expert

    Answer

    The .NET GC uses reachability analysis, not reference counting. Circular references pose no issue unless unreachable from GC roots.

    Q129:

    What is the purpose of the memory barrier in multithreading?

    Expert

    Answer

    Memory barriers prevent reordering and enforce visibility guarantees across threads. They are essential in lock-free algorithms.

    Q130:

    Why does C# support attributes, and how do they enhance program design?

    Expert

    Answer

    Attributes add metadata used by frameworks for configuration, validation, serialization, and behavioral modification.

    Q131:

    What is the difference between a value type stored on the stack vs. boxed value on the heap?

    Expert

    Answer

    Stack value types allocate fast with no GC overhead.

    Boxed values allocate on the heap, increasing memory usage and GC costs.

    Q132:

    What is type erasure, and does C# use it?

    Expert

    Answer

    Type erasure removes generic type information at compile time (Java). C# retains generic metadata at runtime, improving performance and type safety.

    Q133:

    What is the purpose of AppDomain in .NET?

    Expert

    Answer

    AppDomains provided isolation and sandboxing in .NET Framework. .NET Core replaces them with AssemblyLoadContext.

    Q134:

    Why is exception handling considered expensive, and how should it be used?

    Expert

    Answer

    Exceptions trigger stack unwinding, metadata discovery, and context capturing, making them significantly slower than normal execution.

    They should be used only for true exceptional situations—not control flow.

    Q135:

    What is a delegate in C#, and why is it an essential part of the language?

    Expert

    Answer

    A delegate is a type-safe reference to a method. It defines a method signature and allows methods to be stored and invoked dynamically.

    Delegates enable callbacks, event-driven programming, extensibility, and loose coupling by allowing execution of unknown methods at runtime.

    Q136:

    What are multicast delegates, and where are they useful?

    Expert

    Answer

    Multicast delegates can reference multiple methods. When invoked, they call each method sequentially.

    They are used for audit logging, notifications, UI event pipelines, and scenarios requiring multiple actions on a single trigger.

    Q137:

    What is the purpose of built-in delegate types like Action and Func?

    Expert

    Answer

    Action represents methods that return void, while Func represents methods that return a value.

    They reduce the need for custom delegate declarations and simplify modern C# programming.

    Q138:

    How do events build on top of delegates in C#?

    Expert

    Answer

    Events wrap delegates to enforce encapsulation. Only the declaring class can invoke the event, while external components may subscribe or unsubscribe.

    Events implement the publisher–subscriber pattern for decoupled communication.

    Q139:

    Why does C# use the publisher–subscriber model for events?

    Expert

    Answer

    The publisher–subscriber model allows components to react to changes without tight coupling.

    Publishers broadcast notifications without knowing subscribers, improving modularity and scalability.

    Q140:

    What is the significance of async/await in modern C# programming?

    Expert

    Answer

    async/await enables writing asynchronous code in a synchronous style, avoiding callback complexity.

    It improves scalability by freeing threads during I/O waits.

    Q141:

    How does the synchronization context affect async/await behavior?

    Expert

    Answer

    The synchronization context determines where continuation runs after an await.

    UI apps return to the UI thread; ASP.NET Core uses a context-free model to improve throughput.

    Q142:

    Why are thread pools preferred over manually created threads?

    Expert

    Answer

    Thread pools reuse threads, reducing creation overhead and improving performance.

    They optimize concurrency through heuristics and balancing strategies.

    Q143:

    What problems occur when using shared data across multiple threads?

    Expert

    Answer

    Shared data introduces race conditions, stale reads, memory-order issues, and partial updates.

    Proper synchronization is required to ensure correctness.

    Q144:

    What is the purpose of a mutex or semaphore in multi-threading?

    Expert

    Answer

    Mutex allows exclusive access to a resource; Semaphore limits concurrent access.

    Both prevent race conditions but may cause contention when misused.

    Q145:

    What are lock-free operations, and why are they important?

    Expert

    Answer

    Lock-free operations rely on atomic CPU instructions instead of locks.

    They improve scalability and reduce latency in high-concurrency environments.

    Q146:

    What are generics in C#, and why are they critical for type safety and performance?

    Expert

    Answer

    Generics provide compile-time type checking, eliminate unsafe casts, and avoid boxing for value types.

    They enhance performance and enable reusable APIs.

    Q147:

    What are generic constraints, and when should they be used?

    Expert

    Answer

    Generic constraints restrict the types permitted in generics, enabling safer and more expressive generic code.

    They allow accessing members safely based on constraints.

    Q148:

    What is covariance and contravariance in C# generics?

    Expert

    Answer

    Covariance allows using derived types where base types are expected. Contravariance allows the opposite.

    They enable flexible delegate and interface usage.

    Q149:

    How does the List data structure work internally in C#?

    Expert

    Answer

    List uses a dynamically resizing array. When full, it grows and copies elements.

    Provides fast indexing but costly mid-list insertions.

    Q150:

    Why is Dictionary optimized for fast lookups, and how does hashing play a role?

    Expert

    Answer

    Dictionary uses a hash table. The key's hash determines its bucket for near O(1) lookups.

    Good hashing minimizes collisions, improving performance.

    Q151:

    What causes collisions in hash-based collections, and how are they handled?

    Expert

    Answer

    Collisions occur when two keys map to the same bucket. They are handled via chaining or probing.

    Good hash code implementation minimizes collisions.

    Q152:

    What is the purpose of the load factor in hash-based collections?

    Expert

    Answer

    The load factor measures how full a hash table is. When exceeded, resizing and rehashing occur to maintain performance.

    Q153:

    Why is performance tuning important when selecting between List, Queue, Stack, LinkedList, and Dictionary?

    Expert

    Answer

    Each data structure is optimized for specific operations. Incorrect choice leads to wasted CPU cycles and memory overhead.

    Understanding internal behavior is essential for building high-performance systems.

    Q154:

    What happens inside the CLR from compilation to execution? Explain the full pipeline.

    Expert

    Answer

    The CLR pipeline includes:

    • C# code parsed by Roslyn into IL + metadata.
    • IL stored in assemblies (.dll/.exe).
    • CLR loads assemblies via Assembly Loader and verifies IL.
    • JIT compiles IL to native machine code using RyuJIT and tiered compilation.
    • Execution occurs under GC, exception handling, and type-safety rules.
    • Supports JIT, AOT, ReadyToRun, and NativeAOT execution models.
    Q155:

    Explain the .NET Memory Model and how it affects multi-threading.

    Expert

    Answer

    The .NET Memory Model defines visibility and ordering guarantees:

    • Reordering may occur unless prevented by barriers.
    • volatile ensures visibility but not atomicity.
    • lock, Monitor, Interlocked insert full memory fences.
    • Handles cache coherency, tearing, and ABA issues.
    • More relaxed than Java regarding visibility rules.
    Q156:

    How does the CLR allocate memory for value types vs reference types internally?

    Expert

    Answer

    Value types are stored inline on the stack or inside objects. Reference types reside on the managed heap.

    Boxing allocates new objects with headers and method table pointers. Inline struct fields avoid indirection and improve performance.

    Q157:

    What is the internal layout of a .NET object?

    Expert

    Answer

    A .NET object contains:

    • Object Header: Method Table pointer + Sync Block index.
    • Aligned fields with padding.
    • Method Table with hierarchy, vtable, and GC info.
    Q158:

    Explain all GC generations and what makes Gen2 and LOH behave differently.

    Expert

    Answer

    Generations:

    • Gen0: short-lived objects.
    • Gen1: buffer generation.
    • Gen2: long-lived objects; full GC expensive.
    • LOH: >= 85KB, collected only in full GC.
    • POH introduced for pinned objects.
    • GC modes: Server, Workstation, Concurrent.
    Q159:

    What is Tiered Compilation in .NET and why is it important?

    Expert

    Answer

    Tier 0 emits fast, minimally optimized code. Tier 1 recompiles hot methods with optimizations.

    Tiered PGO improves performance for long-running APIs.

    Q160:

    Explain the difference between lock, Monitor, Mutex, Semaphore, SpinLock, and ReaderWriterLockSlim.

    Expert

    Answer

    Differences:

    • lock/Monitor: lightweight, thread-level.
    • Mutex: cross-process synchronization.
    • Semaphore: limits concurrent entries.
    • SpinLock: busy-wait for low contention.
    • ReaderWriterLockSlim: optimized for read-heavy workloads.
    Q161:

    How does async/await work internally at compile-time and runtime?

    Expert

    Answer

    Compiler rewrites async methods into state machines stored as structs or classes.

    Await posts continuations to SynchronizationContext or thread pool.

    Avoid capturing context for performance.

    Q162:

    Explain how string interning works in .NET and when it becomes harmful.

    Expert

    Answer

    Intern pool stores unique string instances for process lifetime.

    Benefits: deduplication of literals. Harmful: unbounded memory use if interning user input.

    Q163:

    What is the difference between Reflection, Reflection.Emit, Expression Trees, and Source Generators?

    Expert

    Answer

    • Reflection: slow metadata inspection.
    • Reflection.Emit: runtime IL generation.
    • Expression Trees: build code graphs; compile to delegates.
    • Source Generators: compile-time code generation.
    Q164:

    How does the .NET ThreadPool actually schedule work?

    Expert

    Answer

    Uses global + per-thread queues, work-stealing, and hill-climbing algorithm to adjust worker count.

    Long-running work should use TaskCreationOptions.LongRunning.

    Q165:

    Explain the different kinds of delegates and how they are represented internally.

    Expert

    Answer

    Delegates can be:

    • Open/closed static
    • Open/closed instance
    • Multicast (invocation list)

    Captured variables create hidden closure classes.

    Q166:

    What is the role of Roslyn in compilation and diagnostics?

    Expert

    Answer

    Roslyn provides AST, syntax trees, semantic models, analyzers, and source generation. It is a compiler-as-a-service.

    Q167:

    Explain covariance and contravariance in delegates and generics in detail.

    Expert

    Answer

    out = covariance, in = contravariance.

    Allows safe substitutability. Includes delegate variance, IEnumerable variance, and array pitfalls.

    Q168:

    What are AppDomains and why are they removed from .NET Core?

    Expert

    Answer

    AppDomains provided isolation but were heavy and difficult to unload.

    .NET Core replaced them with AssemblyLoadContext.

    Q169:

    How does IL differ from CIL and MSIL?

    Expert

    Answer

    IL, CIL, and MSIL are the same thing: platform-independent intermediate language.

    Q170:

    Explain the full exception handling flow in CLR.

    Expert

    Answer

    Flow:

    • Throw triggers stack unwinding.
    • Search for handlers.
    • First-chance and second-chance exceptions.
    • finally, fault blocks executed.
    • Managed/unmanaged transitions handled by the runtime.
    Q171:

    What is the difference between strong naming, signing, and assembly identity?

    Expert

    Answer

    Strong naming gives a unique identity but not security.

    Authenticode signing verifies publisher identity.

    Assembly identity affects binding and version resolution.

    Q172:

    What is metadata in assemblies and how does CLR use it?

    Expert

    Answer

    Metadata includes type, method, field tables, attributes, and generic constraints.

    CLR uses it for JIT compilation, verification, reflection, and type loading.

    Q173:

    What are the key performance traps in C# that senior engineers should avoid?

    Expert

    Answer

    • Excess allocations
    • Boxing
    • Hidden lambda captures
    • LINQ in hot paths
    • Unnecessary locks
    • Sync-over-async
    • Exceptions for flow control

    Curated Sets for C#

    No curated sets yet. Group questions into collections from the admin panel to feature them here.

    Ready to level up? Start Practice