Skip to main content

Amazon Interview C# Interview Questions

Curated Amazon Interview-level C# interview questions for developers targeting amazon interview positions. 173 questions available.

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).
Quick Summary: Value types (int, bool, struct) store their actual data on the stack — copy one and you get two independent values. Reference types (class, string, array) store a pointer on the stack to heap data — copy a reference and both variables point to the same object. This distinction matters a lot when passing objects to methods.
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.

Quick Summary: GC is .NET's automatic memory cleaner. Instead of freeing memory manually, the GC scans the heap, finds objects with no references, and reclaims that memory. It uses generations (Gen0, Gen1, Gen2) — young objects get collected more often since most objects are short-lived.
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(); }


Quick Summary: An interface is a contract — any class that implements it must have these methods and properties. No implementation, just signatures. This lets you write code against the interface rather than a specific class, making things easy to swap, test, and extend.
Q5:

What is abstraction?

Entry

Answer

Hiding internal implementation and exposing only essential features.

Achieved using interfaces or abstract classes.

Quick Summary: Abstraction means hiding complex internals and exposing only what's needed. When you call List.Add(), you don't care how it resizes internally — you just use it. In C#, achieved through interfaces and abstract classes. Keeps code focused on what rather than how.
Q6:

What is encapsulation?

Entry

Answer

Protecting data through access modifiers and properties.

private int age;

public int Age { get; set; }


Quick Summary: Encapsulation means bundling your data and the methods that work on it inside a class, and controlling who can access what. Fields stay private; you expose them through public properties. Prevents outside code from directly tampering with your object's internal state.
Q7:

What are access modifiers in C#?

Entry

Answer

publicprivateprotectedinternalprotected internalprivate protected

Control visibility of classes and members.

Quick Summary: Access modifiers control visibility. public — anyone can access. private — only that class. protected — the class and its subclasses. internal — only within the same assembly. protected internal — subclasses or same assembly. Default for class members is private.
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 )

Quick Summary: Polymorphism means one interface, many behaviors. Call animal.Speak() on a Dog, Cat, or Bird — each responds differently through the same method signature. Achieved via method overriding (runtime) and method overloading (compile-time). One of OOP's most powerful features.
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() { }


Quick Summary: When a child class provides its own version of a parent class method, that's overriding. The parent marks it virtual, the child uses override. At runtime, even holding a base class reference, the child's version gets called — that's the whole point.
Q10:

What is a constructor?

Entry

Answer

A special method executed when an object is created.

public Student() { }


Quick Summary: A constructor is a special method that runs automatically when you create an object with new. It sets up initial state. A class can have multiple constructors with different parameters. If you write none, C# provides a default parameterless one automatically.
Q11:

What is a static constructor?

Entry

Answer

Runs only once per type — initializes static members.

static Student() { }


Quick Summary: A static constructor runs once — the very first time the class is used — and initializes static members. You cannot call it manually or pass parameters. Perfect for one-time setup like loading config or initializing shared resources.
Q12:

What is an exception?

Entry

Answer

An error that occurs during runtime.

Handled using try…catch.

try { } 

catch(Exception ex) { }


Quick Summary: An exception is a runtime error — null reference, divide by zero, file not found, etc. Handle with try-catch-finally. Catch the specific exception type you expect, not the base Exception blindly. Always clean up resources in the finally block.
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)

  • Quick Summary: For value types, both compare values. For reference types, == by default checks if they point to the same object in memory. Equals() can be overridden to compare content. Strings override both to compare content — that's why "hello" == "hello" is true even for different string objects.
    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.
    Quick Summary: C# is Microsoft's general-purpose, object-oriented language that runs on .NET. Think of it as Java's cousin — strongly typed, memory-safe, and packed with modern features like async/await, LINQ, and generics. Used for everything from web APIs to game dev (Unity) to desktop apps.
    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.
    Quick Summary: .NET is the runtime that runs your C# code. It handles memory management, compiles your IL to machine instructions (JIT), and provides a massive standard library. .NET Core/.NET 5+ is the modern cross-platform version; .NET Framework is the older Windows-only one.
    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.
    Quick Summary: A namespace is basically a folder for your code. It groups related classes together and prevents naming conflicts — so MyApp.Models.User and ThirdParty.Models.User never clash. You import them using the 'using' keyword at the top of a file.
    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.

    Quick Summary: By default, value types like int cannot be null. Nullable types (int? or Nullable) allow them to hold null — useful for optional values like database columns. Check with .HasValue, read with .Value, or use ?? for a default fallback.
    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.

    Quick Summary: Arrays are fixed-size — defined upfront, never changes. Lists are dynamic — grow and shrink as needed. Arrays are slightly faster for indexed access. Lists give you Add(), Remove(), Contains() and more. Use List by default unless size is fixed and performance is critical.
    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.
    Quick Summary: var lets the compiler infer the type at compile time — it is not dynamic. var x = 42 is identical to int x = 42 at runtime. Use it when the type is obvious from context, like LINQ results or long generic types. Avoid it when it makes code harder to read.
    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.

    Quick Summary: An enum is a named set of integer constants. Instead of magic numbers like 1=Active, 2=Inactive, you write Status.Active and Status.Inactive. Makes code readable and less error-prone. Under the hood, each value maps to an int starting at 0 by default.
    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.

    Quick Summary: Properties are the clean way to expose class data. Instead of making a field public (risky), you write get and set accessors with validation or logic inside. Auto-properties (public string Name { get; set; }) handle the simple case. Init-only setters allow setting only during object construction.
    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.

    Quick Summary: An indexer lets you access an object using square bracket syntax — just like arrays. Defined with this[int index]. A custom Matrix class could let you do matrix[0, 1] instead of exposing internal arrays. Syntactic sugar that makes your class feel natural to use.
    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.

    Quick Summary: A delegate is a type-safe function pointer — it holds a reference to a method and lets you call it indirectly. You can pass methods as parameters or store them in variables. Action, Func, and Predicate are the built-in generic delegates you will use most of the time.
    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.

    Quick Summary: An event is a delegate with restrictions — only the declaring class can invoke it, but anyone can subscribe. Standard pattern for notifications: button clicks, data changes, etc. Events prevent subscribers from replacing the delegate chain or invoking each other directly.
    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.

    Quick Summary: Both work inside loops. break exits the loop entirely — done, move on. continue skips the rest of the current iteration and jumps to the next one. Think of break as stop the loop and continue as skip this round but keep going.
    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.

    Quick Summary: Both pass by reference but with different rules. ref requires the variable to be initialized before passing — the method can read and modify it. out does not require pre-initialization, but the method must assign a value before returning. Use out for returning multiple values from a 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.

    Quick Summary: A sealed class cannot be inherited — no subclasses allowed. Use it to lock down your design and prevent misuse. The string class in .NET is sealed. It also lets the compiler optimize virtual method calls since no overrides are possible.
    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.

    Quick Summary: A partial class splits one class definition across multiple files — the compiler merges them. Used heavily with auto-generated code like Visual Studio designer files so your handwritten logic stays separate from the generated portion.
    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.

    Quick Summary: The using statement guarantees Dispose() is called when the block ends — even if an exception is thrown. Use with anything holding unmanaged resources: file streams, DB connections, HTTP clients. Without it, you must manually call Dispose() in a finally block every time.
    Q30:

    What is a thread in C#?

    Junior

    Answer

    A thread is the smallest unit of execution.

    It allows multiple tasks to run concurrently.

    Quick Summary: A thread is the smallest unit of execution — a path of code running through your program. By default your app runs on one thread. Additional threads run work in parallel. But threads are expensive and share memory, so misuse causes race conditions and unpredictable bugs.
    Q31:

    What is multithreading?

    Junior

    Answer

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

    Quick Summary: Multithreading lets your app do multiple things simultaneously on separate threads. Great for CPU-heavy work or keeping UIs responsive. Since threads share memory, you need synchronization (locks, semaphores) to avoid data corruption when multiple threads access the same data.
    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.

    Quick Summary: The lock keyword prevents two threads from entering the same block of code at the same time. One thread acquires the lock; others wait. Always lock on a private dedicated object — not this — to avoid accidental interference from outside code.
    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.

    Quick Summary: JIT (Just-In-Time) compilation converts .NET IL code into machine code at runtime, right before it is needed. The first call triggers compilation; subsequent calls use cached machine code. This gives cross-platform portability while still running at near-native speed.
    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.

    Quick Summary: is checks if an object is compatible with a type — returns true or false, never throws. as attempts a cast and returns null on failure instead of throwing InvalidCastException. Modern C# combines both: if (obj is MyType x) checks the type and assigns in one clean step.
    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.

    Quick Summary: The base keyword lets a derived class access its parent's members. Most commonly used to call the parent constructor via base(param), or invoke the parent version of an overridden method via base.MethodName(). Without it, there is no way to reach the parent's overridden implementation.
    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.

    Quick Summary: A readonly struct guarantees all fields are immutable — the compiler enforces it. This lets the runtime safely pass it by reference internally without defensive copies. Use it for small, value-like objects such as coordinates, colors, or time ranges.
    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.

    Quick Summary: A field is a raw variable inside a class — just data storage, no logic. A property wraps it with get and set accessors where you add validation, lazy loading, or computed values. Properties are the public API for your data; fields should always stay private.
    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.

    Quick Summary: An anonymous type lets you create a throwaway object without defining a class: var p = new { Name = "John", Age = 25 }. The compiler generates the class with read-only properties behind the scenes. Used mostly in LINQ projections where you need a temporary data shape.
    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.

    Quick Summary: IEnumerable is the collection — it exposes GetEnumerator() which returns an IEnumerator. IEnumerator is the cursor that walks through items — it has MoveNext(), Current, and Reset(). You implement IEnumerable on your class so it works with foreach. You rarely deal with IEnumerator directly.
    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.

    Quick Summary: Both let you query collections but where the query runs differs. IEnumerable pulls all data to memory first, then filters in C#. IQueryable builds an expression tree and sends it to the data source (like SQL Server) — filtering happens there. For large datasets, always prefer IQueryable.
    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.

    Quick Summary: Extension methods let you add new methods to existing types without touching their source code or subclassing. Write a static method in a static class with this TypeName as the first parameter. They appear as instance methods on that type. All of LINQ is built with extension methods.
    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.

    Quick Summary: A static class cannot be instantiated — you can never do new MathHelper(). All members must also be static. Use it for utility functions that need no state — math operations, string formatting, or extension method containers. Static classes are sealed by default.
    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.

    Quick Summary: Everything in C# ultimately inherits from System.Object (aliased as object). This gives every type — even int — methods like ToString(), Equals(), GetHashCode(), and GetType(). That is why you can assign anything to an object variable, though boxing happens for value types.
    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.

    Quick Summary: A destructor runs when the GC decides to clean up the object — you cannot call it yourself and cannot control when it runs. Avoid using destructors for resource cleanup; use IDisposable and using instead. Destructors delay garbage collection and add measurable overhead.
    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.

    Quick Summary: Method hiding occurs when a derived class defines a method with the same name as the base using the new keyword instead of override. Unlike overriding, if you hold a base class reference, the base version gets called — the derived version only runs through a derived reference.
    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.

    Quick Summary: Early binding resolves method calls at compile time — the compiler knows exactly which method to call, fast and type-safe. Late binding resolves at runtime — used with dynamic, reflection, or virtual dispatch. Late binding is flexible but slower and can fail 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.

    Quick Summary: yield creates a lazy iterator — it returns values one at a time without building a full collection upfront. Execution pauses at yield return and resumes where it left off on the next call. Great for large sequences where you do not want everything loaded into memory at once.
    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.

    Quick Summary: Generics let you write type-safe code that works with any data type. List works for List, List, or any type — no boxing, no casting, compile-time error checking. Before generics, object-based collections were the only option — error-prone and slow.
    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.

    Quick Summary: These control how generic types relate when type parameters have an inheritance relationship. Covariance (out T) lets you use IEnumerable where IEnumerable is expected — safe because you only read. Contravariance (in T) allows Action where Action is expected — safe because you only write.
    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.

    Quick Summary: DI means giving a class its dependencies from outside rather than letting it create them itself. Instead of new SqlRepository() inside a service, you receive an IRepository through the constructor. Makes classes easy to test (swap real for mock) and keeps them loosely coupled. ASP.NET Core has DI built in.
    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.

    Quick Summary: Thread is the raw OS-level execution unit — expensive to create and manage. Task is a higher-level abstraction representing an async operation — managed by the thread pool, much cheaper. Prefer Task and async/await for async work. Use Thread only when you need precise control over execution.
    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.

    Quick Summary: They let you write async code that looks like sync code. Mark a method async, then await any long-running operation like a DB query or HTTP call. The calling thread is freed while waiting — it can handle other requests. Without async/await, you block the thread and kill scalability.
    Q53:

    What is a race condition?

    Junior

    Answer

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

    Quick Summary: A race condition happens when two threads access shared data simultaneously and the result depends on their execution order — which is unpredictable. Two threads both read a counter at 5, both increment, both write 6 — but you expected 7. Fix with lock, Interlocked, or thread-safe collections.
    Q54:

    What is a deadlock?

    Junior

    Answer

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

    Quick Summary: Deadlock is when two or more threads each hold a resource the other needs — so they all wait forever. Thread A holds Lock 1 and needs Lock 2; Thread B holds Lock 2 and needs Lock 1. Prevent by always acquiring locks in the same order, or using timeouts.
    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.

    Quick Summary: Stack stores value types and method call frames — fast allocation, automatic cleanup, limited size. Heap stores reference type objects — slower allocation, reclaimed by GC, can grow large. Stack overflow happens when you recurse too deeply and run out of stack space.
    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.

    Quick Summary: Attributes are metadata tags you attach to classes, methods, or properties using [AttributeName]. Frameworks read them at runtime via reflection to change behavior. Examples: [Required] for validation, [HttpGet] for routing, [Obsolete] to warn callers. You can also write custom attributes.
    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.

    Quick Summary: volatile tells the compiler and CPU not to cache a variable — always read it fresh from memory. Without it, the CPU might cache a value in a register and miss updates from another thread. Use for simple shared flags. For anything complex, use lock or Interlocked instead.
    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.

    Quick Summary: Abstract class: can have implementation, fields, and constructors — a class can inherit only one. Interface: defines only a contract with no implementation (historically) — a class can implement many. Use abstract class for shared behavior. Use interface for capabilities that unrelated types can share.
    Q59:

    What is a virtual method?

    Mid

    Answer

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

    Quick Summary: A virtual method has a default implementation in the base class but can be overridden by subclasses. Mark it virtual in the parent, use override in the child. If not overridden, the base version runs. This is the foundation of runtime polymorphism in C#.
    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.

    Quick Summary: Dispose is the right approach — call it yourself or use using, runs immediately, deterministic. Finalize (destructor) is called by the GC at an unknown time — you cannot control when. Implement both via the Dispose pattern when your class owns unmanaged resources.
    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.

    Quick Summary: Shallow copy duplicates the top-level object but shares references to nested objects — change a nested object in the copy and the original is affected. Deep copy duplicates everything recursively — fully independent. C# has no built-in deep copy; use serialization or manual cloning.
    Q62:

    What is reflection in C#?

    Mid

    Answer

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

    Quick Summary: Reflection lets your code inspect and interact with types at runtime — read class names, get methods, invoke them, read attributes, create instances dynamically. Used heavily in ORMs, serializers, DI containers, and test frameworks. Powerful but slow — avoid in hot code paths.
    Q63:

    What is dynamic type in C#?

    Mid

    Answer

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

    Quick Summary: dynamic skips compile-time type checking entirely — the type resolves at runtime. Useful for COM interop, working with JSON of unknown shape, or calling methods on unknown types at compile time. But you lose IntelliSense and type errors only surface 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.

    Quick Summary: public API is accessible from any assembly — your external contract. internal API is only accessible within the same assembly — useful for sharing code between classes without exposing it to consumers. Use InternalsVisibleTo to grant test projects access to internal members.
    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.

    Quick Summary: An assembly is a compiled .NET file — usually a .dll or .exe. It is the unit of deployment and versioning. It contains compiled IL code, a manifest with metadata, and optional resources. Multiple namespaces can live in one assembly; one namespace can span multiple assemblies.
    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.

    Quick Summary: params lets you pass a variable number of arguments without wrapping them in an array. The method receives them as an array, but callers write Sum(1, 2, 3) instead of Sum(new int[] { 1, 2, 3 }). Must be the last parameter in the signature, and only one params per method.
    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.

    Quick Summary: When a class implements two interfaces with a method of the same name, explicit implementation handles each separately. Written as void IInterface.Method() with no access modifier — accessible only through an interface reference, not the class directly. Resolves ambiguity cleanly.
    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.

    Quick Summary: A readonly field can only be set during declaration or in the constructor — simple and fast, no logic. A property get/set lets you add computation, lazy init, or validation. Properties are more flexible; readonly fields are simpler when you just need an immutable value with no extra logic.
    Q69:

    What is an unsafe context in C#?

    Mid

    Answer

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

    Quick Summary: The unsafe keyword enables pointers and direct memory operations — things C# normally disallows. Used for performance-critical scenarios like native library interop, image processing, or high-speed buffers. Requires /unsafe compiler flag. Outside these niche cases, managed code is always safer.
    Q70:

    What are custom exceptions?

    Mid

    Answer

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

    Quick Summary: Custom exceptions are your own exception classes that extend Exception. They let you signal application-specific errors with meaningful names and carry extra context. OrderNotFoundException is clearer than a generic Exception. By convention, exception class names always end with Exception.
    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.

    Quick Summary: nameof returns the string name of a variable, property, or method at compile time. Instead of hardcoding "PropertyName" (breaks silently on rename), use nameof(PropertyName). Common in INotifyPropertyChanged, argument validation, and logging. Fully refactor-safe.
    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.

    Quick Summary: Shadowing is when a derived class defines a method with the same signature as the base class using the new keyword — not override. Call via a derived reference and you get the derived version; call via a base reference and you get the base version. Usually a code smell; prefer override.
    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.

    Quick Summary: Synchronous code runs step by step, blocking the thread until each operation finishes — simple but wasteful for I/O. Async with await frees the thread while waiting and resumes later. On a web server, async lets one thread handle many concurrent requests instead of sitting idle waiting for DB responses.
    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.

    Quick Summary: Even with GC, memory leaks happen in .NET when objects stay referenced longer than needed. Common causes: unsubscribed event handlers, static collections holding old references, caches that never clear. Use memory profilers (dotMemory, VS Profiler) to find them. Always unsubscribe events when done.
    Q75:

    What is the purpose of StringBuilder?

    Mid

    Answer

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

    Quick Summary: Strings in C# are immutable — every + creates a new string object. Concatenating in a loop creates thousands of temporary strings. StringBuilder is a mutable buffer that appends in-place without intermediary objects. Use it when building strings in loops. For two or three concatenations, + is perfectly fine.
    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.

    Quick Summary: For reference types, == by default checks if two variables point to the same object in memory. object.ReferenceEquals() always does this. But classes can override == and Equals() to compare by content. String does exactly this — two different string objects with the same text are ==.
    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.

    Quick Summary: Value-type semantics: copying means two fully independent values — change one, the other is unaffected. Reference-type semantics: copying means both variables point to the same object — change through one and both see it. Understanding this distinction prevents a huge category of subtle bugs.
    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.

    Quick Summary: Boxing wraps a value type (like int) in a heap-allocated object so it can be treated as object. Unboxing extracts it back. The problem: boxing allocates heap memory and adds GC pressure. In tight loops or large collections, this adds up fast. Use generics (List not ArrayList) to avoid boxing.
    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.

    Quick Summary: IDisposable has one method: Dispose(). Implement it when your class holds unmanaged resources (file handles, DB connections, sockets) or subscribes to events. Wrap in using or call explicitly. The GC will never call Dispose automatically — that is your responsibility.
    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.

    Quick Summary: Generics let you write one implementation that works safely for multiple types. Dictionary works for any combination without casting or boxing. Compile-time type checking catches errors early. Before generics, object-based collections were the only option — error-prone and slow.
    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.

    Quick Summary: const is a compile-time constant — the value is baked into compiled code, must be a primitive or string, implicitly static. readonly is a runtime constant — set at declaration or in the constructor. Prefer readonly for complex values or when the value depends on runtime data.
    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.

    Quick Summary: Overloading: same method name, different parameters — resolved at compile time based on argument types. Overriding: derived class replaces a virtual base method — resolved at runtime based on the actual object type. Overloading is a compile-time feature; overriding is a runtime one.
    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.

    Quick Summary: The GC automatically reclaims heap memory using a generational model. Gen0 holds new objects and is collected most often. Gen1 holds objects that survived one collection. Gen2 holds long-lived objects and is collected rarely. Most objects die young — this model exploits that to stay efficient.
    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.

    Quick Summary: Sync blocks the current thread until completion — simple but wasteful for I/O bound work. Async with await frees the thread during the wait using compiler-generated state machines. On web servers, async means one thread can handle many concurrent requests instead of sitting idle.
    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.

    Quick Summary: Thread-safe means multiple threads can access the same data simultaneously without corrupting it. Without it, two threads might read-modify-write a value at the same time and one update is lost. Use lock, Interlocked operations, ConcurrentDictionary, or immutable types to achieve thread safety.
    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.

    Quick Summary: An immutable object never changes after creation. Since threads can only read it, no locks are needed — no race conditions possible. C# supports this with readonly fields, record types, and init-only properties. Immutability makes concurrent code dramatically simpler and safer.
    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.

    Quick Summary: An instance constructor runs every time you create an object with new — initializes that specific instance. A static constructor runs once — the first time the class is accessed — to set up static members shared across all instances. Neither can be called manually; both run automatically.
    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.

    Quick Summary: A multicast delegate holds references to multiple methods. Invoking it runs all attached methods in sequence. Use += to attach and -= to detach. Events are built on multicast delegates. If any method throws an exception, subsequent methods in the chain will not run.
    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.

    Quick Summary: An event handler is a method matching the event delegate signature — typically void Handler(object sender, EventArgs e). Register with event += Handler, called when the event fires. EventHandler is the standard .NET pattern for typed event data.
    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.

    Quick Summary: Reflection Emit enables creating types, methods, and IL code at runtime dynamically. Used in ORMs, serializers, proxy generators, and dynamic frameworks. Extremely powerful but complex and slow — only reach for it when no other approach works.
    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.

    Quick Summary: Strong naming signs an assembly with a cryptographic key pair. It ensures authenticity, prevents tampering, and enables deployment to the Global Assembly Cache (GAC). Required for assemblies shared across multiple applications on the same machine.
    Q92:

    What is method binding?

    Mid

    Answer

    Method binding connects method calls to implementations.

    Early binding = compile time; late binding = runtime.

    Quick Summary: Method binding connects a method call to its implementation. Early binding happens at compile time — the compiler knows exactly which method to call. Late binding happens at runtime — used with virtual methods, dynamic, and reflection. Early binding is faster and safer.
    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.

    Quick Summary: Attributes add metadata to program elements — classes, methods, properties, parameters. Frameworks read them at runtime via reflection to enforce policies or generate behavior. You can create custom attributes by extending the Attribute base class.
    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.

    Quick Summary: Struct is a value type — stack-allocated, lightweight, copied on assignment, no inheritance. Class is a reference type — heap-allocated, supports inheritance and full OOP. Use struct for small, immutable, data-focused types like Point or Color. Use class for everything else.
    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.

    Quick Summary: Tail recursion is when the very last thing a method does is call itself recursively. Some compilers optimize this into a loop to avoid growing the call stack. C# does not guarantee tail call optimization, but understanding it matters for writing stack-safe recursive algorithms.
    Q96:

    What are anonymous methods?

    Mid

    Answer

    Anonymous methods allow defining inline method bodies.

    They support closures and are often used in event handling.

    Quick Summary: Anonymous methods let you define an inline method body without naming it: button.Click += delegate(object s, EventArgs e) { ... }. They support closures — capturing variables from the enclosing scope. Lambda expressions are the modern, cleaner syntax for the same idea.
    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.

    Quick Summary: Class-level variables (fields) belong to the object and persist for its lifetime — accessible by all methods. Method-level variables exist only during that method call and are gone once it returns. Class-level variables maintain state; method-level variables are for temporary, local computation.
    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.

    Quick Summary: Interfaces define a contract that all implementing types must follow. They enable polymorphism, dependency injection, and loose coupling. A class can implement many interfaces but inherit only one class. They also make unit testing easier by allowing mock implementations to replace real ones.
    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.

    Quick Summary: A sealed class cannot be inherited — no subclasses allowed. It prevents unintended extension and lets the compiler optimize virtual method calls. The string class is sealed. Use it when your class is complete as-is and inheritance would break its design.
    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.

    Quick Summary: const is a compile-time constant — must be assigned at declaration, implicitly static, value baked into caller assemblies. readonly is a runtime constant — can be set in the constructor, works with complex types, and avoids versioning issues since consumers always read the current value.
    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.

    Quick Summary: Boxing converts a value type into a heap-allocated object. Frequent boxing in loops or large collections causes extra memory allocations, GC pressure, and type-check overhead — all of which degrade performance. Avoid by using generic collections like List instead of ArrayList.
    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.

    Quick Summary: Extension methods add functionality to existing types without modifying them. Avoid them when they reduce readability, create ambiguity between methods, or add responsibilities that do not logically belong to the type. Good extension methods feel native; bad ones feel out of place.
    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.

    Quick Summary: The new keyword in a method definition intentionally hides an inherited member, suppressing the compiler warning about shadowing. It signals deliberate hiding rather than accidental name collision. Use it rarely — prefer override for proper polymorphic 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.

    Quick Summary: Nullable value types (int? or Nullable) allow value types to store an additional null state — useful for representing missing or undefined data, especially database fields. Access the value with .Value or the ?? operator, and check existence with .HasValue.
    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.

    Quick Summary: Shallow copy copies only top-level values — reference fields still point to shared objects. Modify a shared nested object and both copies see the change. Deep copy duplicates the entire object graph — fully independent but costs more memory and time. C# has no built-in deep copy utility.
    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.

    Quick Summary: The base keyword accesses parent class members from within a derived class. Use it to call parent constructors (base(params)) or invoke the parent version of an overridden method (base.MethodName()). It is the only way to explicitly call a method you have overridden.
    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.

    Quick Summary: Static constructors initialize static fields and run once before the type is first used — automatically and thread-safely. No parameters, no manual calls. Use when static members need complex initialization that cannot be done inline at declaration.
    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.

    Quick Summary: Implicit conversions happen automatically when there is no risk of data loss — int to long, for example. Explicit conversions require a cast because data loss is possible — double to int truncates the decimal. Always be intentional with explicit casts to avoid silent 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.

    Quick Summary: Partial classes split a class definition across multiple files, merged by the compiler. The most common use is separating auto-generated code (like EF migrations or Winforms designer code) from hand-written logic, keeping each file focused and manageable.
    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.

    Quick Summary: Pass-by-value sends a copy — the method works on its own copy, original unchanged. Pass-by-reference (ref/out) sends the memory address — the method modifies the original variable. Value types default to pass-by-value; reference types pass the reference by value (the object itself is shared).
    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.

    Quick Summary: Overload resolution is how the compiler picks the right method when multiple overloads exist. It considers parameter types, implicit conversions, and specificity. The most specific match wins. Ambiguous calls that the compiler cannot resolve are a compile-time error.
    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.

    Quick Summary: Optional parameters let you define default values in the method signature — callers can omit them. They reduce the need for multiple overloads and simplify API usage. Defined with = in the parameter list: void Send(string msg, bool urgent = false). Must come after required parameters.
    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.

    Quick Summary: The Dispose pattern ensures unmanaged resources (file handles, DB connections, sockets) are released deterministically. Implement IDisposable, write cleanup logic in Dispose(), and optionally add a finalizer as a safety net. Always use the using statement so Dispose is called automatically.
    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.

    Quick Summary: A destructor runs when the GC decides to finalize an object — you cannot predict when. It cannot be called manually and runs on a dedicated finalizer thread. Use it only as a last resort safety net. Prefer Dispose() and the using statement for deterministic resource cleanup.
    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.

    Quick Summary: Strong typing means the compiler knows the exact type of every variable and enforces compatible usage. You cannot accidentally pass a string where an int is expected. This catches entire categories of bugs at compile time instead of runtime and enables better IDE tooling and 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.

    Quick Summary: The CLR is the execution engine for .NET. It handles JIT compilation (IL to machine code), garbage collection, type safety enforcement, exception handling, and thread management. Every C# program runs on top of the CLR — it is what makes .NET cross-platform and memory-safe.
    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.

    Quick Summary: The JIT converts IL to machine code right before execution and applies hardware-specific optimizations like method inlining, dead code elimination, and CPU-tuned instructions. It may recompile hot methods (tiered compilation) with even more aggressive optimizations as the app runs.
    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.

    Quick Summary: C# enforces strict type checking at compile time and the CLR enforces it at runtime. You cannot accidentally treat a string as an integer, cast incompatible types without an explicit cast, or corrupt memory like in C. This makes the language predictable and eliminates whole categories of bugs.
    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.

    Quick Summary: Managed resources are controlled by the CLR — objects, arrays, strings — the GC cleans them up automatically. Unmanaged resources are outside the CLR — file handles, sockets, DB connections — you must release these manually using IDisposable. Forgetting to do so causes resource leaks.
    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.

    Quick Summary: Nullable reference types (C# 8+) make null an explicit opt-in. You declare string? to say "this can be null" and string to mean "this should never be null." The compiler warns you when you dereference something that might be null. This catches null reference exceptions before they happen at runtime.
    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.

    Quick Summary: volatile ensures that reads and writes to a field always go directly to memory — the CPU and compiler cannot cache or reorder them. Without it, one thread might read a stale cached value that another thread already updated. Use it for simple shared flags between threads.
    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.

    Quick Summary: Process memory is everything the OS allocates to your app — stack, heap, DLL code, native buffers, OS handles. Managed heap is just the CLR-controlled subset where .NET objects live and the GC operates. All managed heap is part of process memory, but not all process memory is managed heap.
    Q123:

    How does string immutability help performance and safety?

    Expert

    Answer

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

    Quick Summary: Because strings are immutable, they are inherently thread-safe — no locks needed when reading across threads. The runtime can also intern string literals (reuse the same object for equal strings) to save memory. The downside: every modification creates a new string, so use StringBuilder for heavy concatenation.
    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.

    Quick Summary: Metadata in a .NET assembly describes everything about your types — class names, method signatures, parameter types, attributes, generic constraints. The CLR uses it for JIT compilation, type loading, reflection, and serialization. It is what makes .NET assemblies self-describing without needing header files.
    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.

    Quick Summary: Boxing allocates a new object on the heap and copies the value into it — that is a heap allocation plus GC tracking overhead. Unboxing requires a type check plus a copy back out. In a tight loop or large collection, thousands of box/unbox operations visibly degrade performance. Use generics to avoid it.
    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.

    Quick Summary: A weak reference lets you reference an object without preventing the GC from collecting it. If memory is low, the GC can reclaim the object even though you hold a weak reference. Useful for caches where you want to keep data if possible but not force it to stay alive.
    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.

    Quick Summary: Reflection lets you inspect types, methods, and properties at runtime and invoke them dynamically. The risks: it is significantly slower than direct calls, it bypasses compile-time type safety, it can expose private members, and it makes code harder to refactor and analyze statically.
    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.

    Quick Summary: The .NET GC uses reachability analysis, not reference counting. It traces from GC roots (static fields, stack variables, CPU registers) and marks everything reachable. Circular references are not a problem — if neither object in the cycle is reachable from a root, both get collected.
    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.

    Quick Summary: A memory barrier prevents the CPU and compiler from reordering instructions across it. Without barriers, one thread might write data in a different order than you expect, and another thread reads it in that wrong order. The lock keyword implicitly adds full memory barriers on entry and exit.
    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.

    Quick Summary: Attributes let frameworks drive behavior through metadata instead of hardcoded logic. [Required] triggers validation, [HttpGet] configures routing, [JsonIgnore] controls serialization — all without touching the framework's source code. They separate configuration from logic cleanly.
    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.

    Quick Summary: A stack value type is allocated in the method's stack frame — no heap allocation, no GC tracking, zero overhead when the method returns. A boxed value lives on the heap — it needs a GC header, is tracked by the collector, and adds allocation pressure. Stack allocation is always cheaper.
    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.

    Quick Summary: Type erasure (used in Java) removes generic type info at compile time — at runtime, List and List are the same List. C# does the opposite — it retains generic type info at runtime. This means better performance (no boxing for value types), accurate reflection, and safer runtime behavior.
    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.

    Quick Summary: In .NET Framework, AppDomains provided isolation between parts of an application in the same process — you could load and unload assemblies independently. In .NET Core they were removed because they were too complex and slow. AssemblyLoadContext is the modern replacement for dynamic assembly loading.
    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.

    Quick Summary: Exceptions trigger stack unwinding, handler lookup, and context capture — all expensive operations compared to normal code execution. Use them only for genuinely exceptional situations — not for control flow like checking if a key exists in a dictionary. For expected failures, use return values or TryXxx patterns.
    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.

    Quick Summary: A delegate is a type-safe reference to a method — it stores a method and lets you call it indirectly. It enables callbacks, events, and passing behavior as a parameter. Delegates are the foundation of events, LINQ, and the entire functional-style programming model in C#.
    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.

    Quick Summary: A multicast delegate holds a list of methods and calls them all in sequence when invoked. Use += to add a method and -= to remove it. Events are built on this. Useful for audit logging, notification pipelines, or any scenario where multiple subscribers need to react to one 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.

    Quick Summary: Action is a built-in delegate for methods that return void. Func is for methods that return a value — the last type parameter is the return type. They eliminate the need to define custom delegate types for most scenarios and work seamlessly with lambdas and LINQ.
    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.

    Quick Summary: Events wrap a delegate so only the declaring class can invoke it — external code can only subscribe or unsubscribe. This protects the invocation list from being replaced or triggered by outsiders. Events implement the publisher-subscriber pattern for decoupled component 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.

    Quick Summary: In the pub-sub model, publishers raise events without knowing who is listening. Subscribers register and react independently. This removes direct dependencies between components — you can add or remove subscribers without changing the publisher. Great for UI events, domain events, and plugin systems.
    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.

    Quick Summary: async/await lets you write non-blocking code that reads like normal sequential code. Without it, async operations required callbacks or manual thread management. With it, the compiler generates a state machine that suspends and resumes execution automatically. Crucial for scalable web APIs and responsive UIs.
    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.

    Quick Summary: The synchronization context captures "where" code should continue after an await. In WPF/WinForms, continuations run back on the UI thread. In ASP.NET Core, there is no synchronization context — continuations run on any thread pool thread. Add ConfigureAwait(false) in libraries to avoid capturing the context unnecessarily.
    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.

    Quick Summary: Creating a thread is expensive — it allocates a stack, registers with the OS, and takes time. Thread pools reuse a fixed set of threads for many short tasks. They also auto-tune the number of threads based on workload. For async I/O-bound work, the pool is efficient; for long-running CPU work, use dedicated threads.
    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.

    Quick Summary: Shared mutable data across threads leads to race conditions (two threads modify at the same time), stale reads (one thread caches an old value), and partial updates (a write is only halfway done when another thread reads). Always protect shared state with locks, atomic operations, or immutable data.
    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.

    Quick Summary: Mutex allows only one thread (or process) at a time to access a resource — useful for cross-process locking. Semaphore limits concurrent access to N threads at once — useful for rate-limiting or connection pools. Both block waiting threads; overusing them causes contention and performance issues.
    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.

    Quick Summary: Lock-free operations use atomic CPU instructions (compare-and-swap) instead of locks — no thread ever blocks waiting. This improves scalability in high-concurrency scenarios where lock contention would be a bottleneck. The Interlocked class in C# provides lock-free atomic operations.
    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.

    Quick Summary: Generics provide compile-time type checking — catch type errors before you ship. They eliminate boxing for value types (huge performance win for collections), remove unnecessary casts, and produce reusable code that works for any type. The backbone of the entire .NET collection library.
    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.

    Quick Summary: Generic constraints (where T : ...) restrict what types can be used as T. Common constraints: class (reference type), struct (value type), new() (has parameterless constructor), or a specific interface. They let you safely call members on T that the constraint guarantees exist.
    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.

    Quick Summary: Covariance (out T on interfaces like IEnumerable) lets you use a more derived type where a base is expected — safe for read-only scenarios. Contravariance (in T on Action) lets you use a more base type — safe for write-only scenarios. Applies to interfaces and delegates, not classes.
    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.

    Quick Summary: List internally uses an array. When it runs out of space, it allocates a new array twice the size and copies everything over. This gives O(1) average Add() and O(1) indexed access, but O(n) insertion or removal in the middle. It is the go-to collection for most scenarios.
    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.

    Quick Summary: Dictionary uses a hash table — it computes a hash of the key, finds the right bucket, and stores the value there. This gives near O(1) lookups on average. When many keys hash to the same bucket (collisions), performance degrades. A good GetHashCode() implementation keeps collisions minimal.
    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.

    Quick Summary: Collisions happen when two different keys produce the same hash bucket. .NET's Dictionary handles this with chaining — multiple entries in the same bucket form a linked list. Too many collisions slow lookups from O(1) to O(n). Implement GetHashCode() to spread values evenly across buckets.
    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.

    Quick Summary: The load factor is the ratio of entries to buckets. When it exceeds a threshold (default 0.72 in many implementations), the collection resizes — allocates a larger array and rehashes everything. This keeps lookup performance near O(1). Pre-size your dictionary with an initial capacity if you know the count.
    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.

    Quick Summary: List for sequential access with fast indexing. Dictionary for key-based O(1) lookups. Queue/Stack for FIFO/LIFO access patterns. LinkedList for frequent mid-list insertions. Choosing the wrong one — like using List.Contains() instead of HashSet — can turn O(1) into O(n) and tank performance at scale.
    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.
    Quick Summary: Your C# code is compiled by Roslyn into IL (Intermediate Language) stored in an assembly. At runtime, the CLR loads the assembly, verifies the IL, then JIT-compiles it to native machine code on first execution. From then on, the native code runs directly. GC, exception handling, and type safety are managed throughout.
    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.
    Quick Summary: The .NET memory model defines what ordering guarantees threads have. Without synchronization, the CPU or compiler may reorder reads and writes. volatile ensures visibility (no caching), lock adds full memory barriers, and Interlocked provides atomic operations. Writing lock-free code correctly requires understanding all three.
    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.

    Quick Summary: Value types are stored inline — on the stack for locals, or embedded directly in the containing object on the heap. Reference types always go on the managed heap with a header and method table pointer. Boxing creates a heap-allocated wrapper around a value type, which is why it costs a heap allocation.
    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.
    Quick Summary: Every .NET object on the heap has a header containing a Method Table pointer (links to the type's vtable and metadata) and a Sync Block index (used for lock and GetHashCode). After the header come the object's fields, aligned for the platform. Understanding this explains why small objects still have memory overhead.
    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.
    Quick Summary: Gen0 collects frequently and cheaply — most objects die here. Gen1 is a buffer between Gen0 and Gen2. Gen2 collects rarely but is expensive — it scans the full heap. The Large Object Heap (LOH, objects >= 85KB) is collected only during full Gen2 GCs and is not compacted by default, leading to fragmentation.
    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.

    Quick Summary: Tiered compilation runs methods at Tier 0 first with minimal optimization for fast startup. As methods get called repeatedly (hot paths), the JIT recompiles them at Tier 1 with full optimizations. With PGO (Profile-Guided Optimization), it uses actual runtime data to make even smarter optimization decisions.
    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.
    Quick Summary: lock and Monitor: lightweight, process-local, same thread only. Mutex: cross-process, heavier, supports named mutexes. Semaphore: limits N concurrent threads. SpinLock: avoids context switch for very short critical sections. ReaderWriterLockSlim: allows many concurrent readers but exclusive write access.
    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.

    Quick Summary: The compiler transforms an async method into a state machine struct. Each await point becomes a state. When awaited work completes, the continuation is posted to the SynchronizationContext or thread pool. No thread is blocked during the wait — the thread is returned to the pool and picked up again when needed.
    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.

    Quick Summary: String interning stores one shared instance of each unique string literal in a process-wide pool. Two equal string literals share the same object in memory. This saves memory for repeated strings. The danger: interning user input or dynamic strings fills the pool permanently, causing memory growth that the GC cannot reclaim.
    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.
    Quick Summary: Reflection: slow runtime inspection, good for general-purpose tools. Reflection.Emit: generates IL at runtime, used in ORMs and proxies. Expression Trees: build code as data structures, compile to delegates, used in LINQ providers. Source Generators: generate code at compile time — zero runtime cost, the modern preferred approach.
    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.

    Quick Summary: The ThreadPool maintains a global queue and per-thread local queues. Threads steal work from each other when idle. A hill-climbing algorithm adjusts the thread count based on throughput measurements. For long-running work (> 0.5s), use TaskCreationOptions.LongRunning to get a dedicated thread instead.
    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.

    Quick Summary: A delegate internally stores a method pointer and a target object. Static method delegates have no target. When you capture variables in a lambda, the compiler generates a hidden closure class to hold them. Multicast delegates maintain an invocation list array — invoking iterates and calls each entry.
    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.

    Quick Summary: Roslyn is the C# and VB compiler exposed as an API (compiler-as-a-service). It provides syntax trees, semantic models, and diagnostics that tools like Visual Studio, analyzers, and code fixers use. Source generators hook into Roslyn to generate code at compile time based on your existing code.
    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.

    Quick Summary: Covariance (out T) on interfaces like IEnumerable means IEnumerable is assignable to IEnumerable. Contravariance (in T) on delegates like Action means Action is assignable to Action. These only apply to interfaces and delegates — not concrete generic classes.
    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.

    Quick Summary: AppDomains in .NET Framework let you load and unload assemblies independently within one process. They were removed in .NET Core because they were expensive, rarely used correctly, and did not work cross-platform. AssemblyLoadContext is the lightweight replacement for plugin and isolated assembly loading scenarios.
    Q169:

    How does IL differ from CIL and MSIL?

    Expert

    Answer

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

    Quick Summary: IL, CIL (Common Intermediate Language), and MSIL (Microsoft Intermediate Language) all refer to the same thing — the platform-independent bytecode that C# compiles to. CIL is the official ECMA standard name. MSIL is the old Microsoft name. IL is the common shorthand everyone uses.
    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.
    Quick Summary: When an exception is thrown, the CLR unwinds the call stack frame by frame, searching for a matching catch handler. First-chance exceptions are raised before any handler runs (useful for debuggers). Finally and fault blocks always run during unwinding. Unhandled exceptions terminate the process.
    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.

    Quick Summary: Strong naming gives an assembly a unique identity via a public/private key pair — prevents two assemblies with the same name from conflicting. It does not verify the publisher's identity. Authenticode signing (via a certificate) proves who published the assembly. Both can coexist on the same assembly.
    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.

    Quick Summary: Assembly metadata contains tables describing every type, method, field, parameter, and attribute in the assembly. The CLR reads this during type loading to understand what to JIT-compile, how to lay out objects in memory, and what to expose through reflection. It makes assemblies completely self-describing.
    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
    Quick Summary: Key C# performance traps: excessive allocations in hot paths, boxing value types, unintended lambda closures capturing references, LINQ chains that re-enumerate, lock contention on shared state, sync-over-async (blocking async code with .Result), and using exceptions for normal control flow.

    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