.NET Interview Questions and Answers


1. What is the .NET Framework? (Historical Context)
  • The .NET Framework was Microsoft's original proprietary framework for building applications primarily on Windows. It included the CLR, FCL (Framework Class Library), and various application models (WinForms, WPF, ASP.NET Web Forms/MVC).
2. What is .NET Core? (Historical Context)
  • .NET Core was a cross-platform, open-source, and modular successor to the .NET Framework. It was designed for modern application development, cloud-native apps, and microservices, supporting Windows, macOS, and Linux.
3. What is the current state of .NET (e.g., .NET 6, 7, 8)?
  • Starting with .NET 5, Microsoft unified the .NET ecosystem. There is now just "'.NET'" with version numbers (e.g., .NET 8). It's cross-platform, open-source, and the successor to both .NET Framework and .NET Core.
4. What are the key components of the .NET ecosystem?
  • .NET Runtime (CLR - Common Language Runtime): Executes code, provides services like garbage collection and exception handling.
  • Base Class Library (BCL): A comprehensive set of types and utilities for common tasks.
  • SDK (Software Development Kit): Includes the CLI, compilers, and tools for building .NET applications.
  • Compilers: C#, F#, VB.NET compilers that compile code into Intermediate Language (IL).
  • JIT (Just-In-Time) Compiler: Compiles IL code into native machine code at runtime.
  • Garbage Collector (GC): Automatically manages memory by reclaiming memory used by objects that are no longer reachable.
5. What is the Common Language Runtime (CLR)?
  • The CLR is the runtime environment for .NET code. It manages the execution of .NET programs, handling tasks like memory management, garbage collection, security, and exception handling.
6. What is the Base Class Library (BCL)?
  • The BCL is a foundational library that provides a wide range of types and functionalities for common programming tasks, such as data structures, file I/O, networking, and threading.
7. What is Intermediate Language (IL) or Common Intermediate Language (CIL)?
  • IL is the platform-independent, low-level code that .NET source code (like C#) is compiled into. It's similar to assembly language but is not specific to any particular CPU architecture. The JIT compiler then translates IL into native machine code at runtime.
8. What is the Just-In-Time (JIT) Compiler?
  • The JIT compiler is part of the CLR. It translates IL code into native machine code just before the code is executed. This allows .NET applications to run on different architectures and provides performance optimizations based on the runtime environment.
9. What is the Garbage Collector (GC)?
  • The GC is responsible for automatic memory management in .NET. It tracks objects in memory and reclaims the memory used by objects that are no longer being used by the application, preventing memory leaks.
10. What is the difference between managed and unmanaged code?
  • Managed Code: Code that runs under the control of the CLR. The CLR handles memory management, type safety, and other services. C#, VB.NET, and F# code compiled for .NET is managed code.
  • Unmanaged Code: Code that runs outside the CLR's control (e.g., native C++ code). Memory management and other resources must be handled manually.
11. What is an Assembly in .NET?
  • An assembly is the basic unit of deployment and versioning in .NET. It's a file (usually a .dll or .exe) that contains IL code, metadata, and optional resources.
12. What is the Global Assembly Cache (GAC)? (Mostly for .NET Framework)
  • The GAC is a machine-wide repository for storing and sharing strong-named assemblies (assemblies with a unique identity, including version information). It was used primarily in the .NET Framework to avoid DLL Hell. Less relevant in modern .NET where applications are typically deployed side-by-side.
13. What are Value Types and Reference Types in C#?
  • Value Types: Store their data directly. Examples include primitive types (int, bool, struct). They are allocated on the stack (usually) and passed by value.
  • Reference Types: Store a reference (memory address) to their data. Examples include classes, interfaces, delegates, arrays, and strings. They are allocated on the heap and passed by reference (the reference itself is passed by value).
14. Explain Boxing and Unboxing.
  • Boxing: The process of converting a value type instance to an object or to an interface type implemented by the value type. This involves allocating memory on the heap and copying the value's data there.
  • Unboxing: The process of converting an object back to a value type. This requires a cast and involves checking if the object is a boxed instance of the target value type and copying the data from the heap back to the stack. Both boxing and unboxing can impact performance.
15. What is a Struct in C#?
  • A struct is a value type that is typically used for small data structures. Unlike classes, structs are allocated on the stack (for local variables) or inline within objects. They don't support inheritance (except from System.ValueType).
16. What is the difference between const and readonly?
  • const: Used for compile-time constants. The value must be assigned at declaration and cannot be changed. Can only be used with primitive types, strings, and null. Implicitly static.
  • readonly: Used for runtime constants. The value can be assigned at declaration or in the constructor(s) of the class/struct. It cannot be changed after the constructor finishes. Can be used with any data type. Can be instance-level or static.
17. What is the using statement?
  • The using statement provides a convenient syntax for working with objects that implement the IDisposable interface. It ensures that the object's Dispose() method is called automatically when the object goes out of scope, even if an exception occurs.
18. What is the purpose of the IDisposable interface?
  • The IDisposable interface is used to release unmanaged resources (like file handles, network connections) held by an object. Objects that hold such resources should implement this interface and provide cleanup logic in the Dispose() method.
19. Explain Encapsulation in C#.
  • Encapsulation is an OOP principle of bundling data (fields) and methods that operate on the data within a single unit (a class) and restricting direct access to the data from outside the class. Access is controlled via access modifiers (public, private, protected, internal). Properties are commonly used to provide controlled access to fields.
20. Explain Inheritance in C#.
  • Inheritance is an OOP principle that allows a new class (derived class or subclass) to inherit properties and methods from an existing class (base class or superclass). This promotes code reusability and establishes an "is-a" relationship. C# supports single inheritance for classes.
21. Explain Polymorphism in C#.
  • Polymorphism means "many forms." In C#, it allows objects of different classes to be treated as objects of a common base class or interface. This enables writing generic code that can work with various types. Achieved through method overriding (runtime polymorphism) and method overloading or interfaces (compile-time/runtime polymorphism).
22. Explain Abstraction in C#.
  • Abstraction is an OOP principle of hiding complex implementation details and showing only the essential features of an object. It's achieved using abstract classes and interfaces.
23. What are Abstract Classes and Abstract Methods?
  • An abstract class is a class that cannot be instantiated directly. It can contain abstract methods (methods declared without an implementation) and concrete methods (methods with implementation). Derived classes must implement all abstract methods.
  • An abstract method is a method declared in an abstract class without a body. It must be overridden by non-abstract derived classes.
24. What is an Interface in C#?
  • An interface is a contract that defines a set of methods, properties, events, or indexers that a class or struct must implement. It specifies "what" a class must do, without providing implementation details. A class can implement multiple interfaces.
25. What is the difference between an Abstract Class and an Interface?
  • Abstract Class: Can have abstract and concrete methods. Can have fields and constructors. Supports inheritance (single inheritance for classes). Can have access modifiers.
  • Interface: Defines a contract. Cannot have fields (prior to C# 8). Cannot have constructors. Supports multiple implementation. Members are implicitly public (prior to C# 8, C# 8+ allows explicit access modifiers for default interface methods).
26. What is Method Overloading?
  • Method overloading allows a class to have multiple methods with the same name but different parameter lists (different number of parameters, different types of parameters, or different order of parameter types). The return type does not differentiate overloaded methods.
27. What is Method Overriding?
  • Method overriding allows a derived class to provide a specific implementation for a method that is already defined in its base class. The method signature (name, return type, and parameters) must be the same. The base class method must be marked with virtual, abstract, or override, and the derived class method must be marked with override.
28. What is the difference between virtual, override, and new keywords in inheritance?
  • virtual: Used in the base class to indicate that a method can be overridden by derived classes.
  • override: Used in the derived class to provide a new implementation for a virtual or abstract method from the base class.
  • new: Used in the derived class to hide a member of the base class with the same name. This is not polymorphism; the base class member is still accessible by casting the derived class object to the base class type.
29. What is a Delegate in C#?
  • A delegate is a type that represents references to methods with a particular parameter list and return type. It's like a type-safe function pointer. Delegates are used to implement event handling, callbacks, and anonymous methods.
30. What are Events in C#?
  • Events are a way for a class to provide notifications to other classes when something interesting happens. They are based on the delegate model. A class that raises an event (the publisher) declares an event member, and other classes (subscribers) can attach methods (event handlers) to the event using delegates.
31. What are Anonymous Methods and Lambda Expressions?
  • Anonymous Methods: An inline block of code that can be used where a delegate type is expected. Introduced in C# 2.0.
  • Lambda Expressions: A more concise syntax for creating anonymous methods. Introduced in C# 3.0. They are widely used with LINQ.
32. What is LINQ (Language Integrated Query)?
  • LINQ is a set of technologies for querying data from various data sources (like collections, databases, XML) using a consistent syntax integrated into the C# language. It provides query syntax and method syntax.
33. Explain Asynchronous Programming with async and await.
  • Asynchronous programming allows an application to perform long-running operations (like I/O operations or network calls) without blocking the main thread.
    • async: Modifier used on a method to indicate that it contains one or more await expressions.
    • await: Operator used within an async method to pause the execution of the method until the awaited asynchronous operation (a Task) completes. The thread is released back to the thread pool to perform other work while waiting.
34. What are Tasks in C#?
  • Task (and Task<>) represents an asynchronous operation. A Task represents an asynchronous operation that does not return a value, while Task<> represents an asynchronous operation that returns a value of type T. They are part of the Task Parallel Library (TPL).
35. What is Dependency Injection (DI)?
  • DI is a design pattern used to achieve Inversion of Control (IoC). Instead of objects creating their dependencies, the dependencies are injected into the object from an external source (usually a DI container). This promotes loose coupling, testability, and maintainability.
36. How is Dependency Injection implemented in ASP.NET Core?
  • ASP.NET Core has a built-in DI container. Services (dependencies) are registered in the ConfigureServices method (or equivalent in newer versions) in Startup.cs (or Program.cs). Dependencies are then injected into constructors of classes that need them (like controllers, services, middleware).
37. What are the different service lifetimes in ASP.NET Core DI?
  • Transient: A new instance of the service is created every time it is requested.
  • Scoped: A new instance of the service is created once per scope (e.g., once per HTTP request in a web application).
  • Singleton: A single instance of the service is created for the entire lifetime of the application.
38. What is ASP.NET Core?
  • ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, internet-connected applications, including web apps, APIs, and microservices.
39. What is Middleware in ASP.NET Core?
  • Middleware are components that are assembled into an application pipeline to handle requests and responses. Each middleware component can process an incoming HTTP request, perform actions, and pass the request to the next middleware in the pipeline, or short-circuit the pipeline.
40. How is the middleware pipeline configured in ASP.NET Core?
  • The middleware pipeline is configured in the Configure method in Startup.cs (or directly in Program.cs in newer versions) using the IApplicationBuilder interface (e.g., app.UseRouting(), app.UseAuthorization()).
41. What is the difference between IHostingEnvironment and IWebHostEnvironment? (For older ASP.NET Core versions)
  • IHostingEnvironment was used in older ASP.NET Core versions to get information about the application's hosting environment (e.g., environment name like "Development", "Staging", "Production").
  • IWebHostEnvironment replaced it in ASP.NET Core 3.0 and later, providing the same information along with the content root path and web root path.
42. What is the difference between IHostEnvironment and IWebHostEnvironment? (For modern .NET)
  • IHostEnvironment is a more general interface providing basic environment information (environment name, application name, content root path).
  • IWebHostEnvironment inherits from IHostEnvironment and adds web-specific properties like WebRootPath. Use IWebHostEnvironment for web applications.
43. What is Configuration in ASP.NET Core?
  • ASP.NET Core uses a flexible configuration system that allows you to load configuration settings from various sources (like appsettings.json, environment variables, command-line arguments, Azure Key Vault, etc.) and access them through the IConfiguration interface.
44. What is the Options Pattern in ASP.NET Core?
  • The Options pattern provides a way to strongly type configuration settings and inject them into classes using DI. This makes configuration access type-safe and testable. It involves defining configuration classes and registering them with the DI container using IOptions or IOptionsSnapshot.
45. What is Entity Framework Core (EF Core)?
  • EF Core is a lightweight, extensible, open-source, and cross-platform Object-Relational Mapper (ORM) for .NET. It allows developers to work with a database using .NET objects (entities) without writing most of the data-access plumbing code.
46. What are Migrations in EF Core?
  • Migrations are a way to manage database schema changes over time. They allow you to evolve your database schema as your entity model changes. EF Core tracks these changes and generates code to apply or revert them.
47. What is the difference between Code-First and Database-First approaches in EF Core?
  • Code-First: You define your entity classes first, and EF Core generates the database schema based on your code using migrations. This is the recommended approach in modern .NET.
  • Database-First: You start with an existing database, and EF Core scaffolds entity classes and a DbContext based on the database schema.
48. What is the DbContext in EF Core?
  • The DbContext is the primary class responsible for interacting with the database. It represents a session with the database and provides properties that represent collections of your entities (DbSet<>). It tracks changes to entities, performs queries, and saves data.
49. What is LINQ to Entities?
  • LINQ to Entities is the LINQ provider for EF Core. It allows you to write LINQ queries against your DbSet<> properties in the DbContext. EF Core translates these LINQ queries into SQL queries that are executed against the database.
50. What is the difference between ToList() and AsEnumerable() in LINQ?
  • ToList(): Immediately executes the query and materializes the results into a List in memory.
  • AsEnumerable(): Does *not* execute the query immediately. It returns an IEnumerable that represents the query. The query is executed when you iterate over the collection (e.g., in a foreach loop or when calling other LINQ operators like ToList() or ToArray() later). When used with EF Core, AsEnumerable() can cause subsequent filtering/sorting to happen in memory rather than in the database, which can be inefficient.
51. What is the difference between IQueryable and IEnumerable?
  • IQueryable: Represents a query that is executed against a data source (like a database) using a query provider (like LINQ to Entities). Queries are typically translated into the data source's native query language (e.g., SQL) and executed remotely. Subsequent LINQ operations are appended to the query expression before execution.
  • IEnumerable: Represents an in-memory collection of objects. LINQ operations on IEnumerable are executed in memory using LINQ to Objects.
  • When working with EF Core, use IQueryable for building queries that should be executed in the database, and convert to IEnumerable or List when you need to work with the data in memory.
52. What is Lazy Loading in EF Core?
  • Lazy loading is a technique where related entities are loaded from the database automatically the first time they are accessed, rather than loading them along with the principal entity. This requires navigation properties to be marked as virtual. Can lead to N+1 query problems.
53. What is Eager Loading in EF Core?
  • Eager loading is a technique where related entities are loaded from the database along with the principal entity in a single query. This is done using the Include() and ThenInclude() methods in LINQ queries. Generally preferred over lazy loading to avoid N+1 issues.
54. What is Explicit Loading in EF Core?
  • Explicit loading is a technique where related entities are loaded explicitly at a later point after the principal entity has been loaded. This is done using the Load() method or Entry(...).Collection/Reference(...).Load() on the DbContext entry for the entity.
55. What is the difference between Add and Attach in EF Core?
  • DbContext.Add(entity): Adds a new entity to the context. EF Core assumes the entity is new and will insert it into the database when SaveChanges() is called.
  • DbContext.Attach(entity): Attaches an existing entity to the context. EF Core assumes the entity already exists in the database and does not track any changes by default. It's used when you have an entity instance that was retrieved outside the current context and you want to start tracking it. You can then manually set its state (e.g., to Modified) if needed.
56. What is the purpose of the using directive?
  • The using directive imports namespaces into a code file, making the types within those namespaces accessible without needing to use the fully qualified name.
57. What is a Namespace?
  • A namespace is a way to organize code and prevent naming conflicts. It provides a scope for types (classes, structs, enums, interfaces, delegates).
58. What is the difference between System.String and string?
  • There is no difference. string is simply an alias in C# for the System.String class in the .NET BCL.
59. What is the difference between System.Int32 and int?
  • There is no difference. int is an alias in C# for the System.Int32 value type. This applies to most primitive types (bool/System.Boolean, float/System.Single, etc.).
60. What is the purpose of the sealed keyword?
  • The sealed keyword can be applied to a class to prevent other classes from inheriting from it. It can also be applied to a method override to prevent further overriding in derived classes.
61. What is the purpose of the static keyword?
  • The static keyword declares a member (field, property, method, class, constructor) that belongs to the type itself rather than to any specific instance of the type. Static members are accessed directly using the class name. Static classes cannot be instantiated and can only contain static members.
62. What is the difference between a static class and a singleton pattern?
  • Static Class: Cannot be instantiated. All members are static. Lifetime is the application lifetime. Cannot implement interfaces or inherit from classes (except Object).
  • Singleton Pattern: A design pattern that ensures only one instance of a class exists throughout the application's lifetime. The class is responsible for creating and providing access to that single instance. The class itself is not necessarily static (it has instance members), but the access point to the instance is typically static. Can implement interfaces and inherit from classes.
63. What are Extension Methods?
  • Extension methods allow you to add new methods to existing types without modifying the type itself. They are static methods defined in a static class, but they are called as if they were instance methods on the extended type. The first parameter of an extension method is the type being extended, prefixed with the this keyword.
64. What are Generics?
  • Generics allow you to define classes, interfaces, methods, and delegates that work with different types without sacrificing type safety or performance. They enable creating reusable code that can operate on objects of various types while still providing compile-time type checking.
65. What is the purpose of the yield keyword?
  • The yield return statement is used in iterator blocks to provide an element of a sequence. It allows you to implement custom iteration without creating a temporary collection in memory. The state of the iterator is preserved between calls.
66. What are Attributes in C#?
  • Attributes are declarative tags that can be applied to code elements (assemblies, types, members, parameters, return values). They provide metadata about the code that can be accessed at runtime using reflection. Examples include [Serializable], [Obsolete], [Test] (from testing frameworks).
67. What is Reflection?
  • Reflection is the ability of a program to examine and modify its own structure and behavior at runtime. In .NET, you can use reflection to inspect metadata about types, invoke methods, create objects, and access properties/fields dynamically.
68. What is the purpose of the dynamic keyword?
  • The dynamic keyword is used to declare a variable whose type is not known at compile time. Type checking is deferred until runtime. This allows for scenarios like interacting with dynamic languages or COM objects, but it loses compile-time safety.
69. What is the difference between is and as operators?
  • is: Checks if an object is compatible with a given type. It returns true or false. It doesn't throw an exception. Can also be used for pattern matching in newer C# versions.
  • as: Attempts to cast an object to a given type. If the cast is successful, it returns the object cast to the target type; otherwise, it returns null. It doesn't throw an exception. Can only be used with reference types or nullable value types.
70. What is the difference between throw ex and throw;?
  • throw ex;: Throws the provided exception object. If this is caught within a catch block, it resets the stack trace to the point where throw ex; is called, losing the original exception's call stack.
  • throw;: Rethrows the caught exception without losing the original stack trace information. This is the preferred way to rethrow an exception within a catch block.
71. What is Threading?
  • Threading is the ability to execute multiple parts of a program concurrently. A thread is a lightweight process that can run independently within a process.
72. What is the Global Interpreter Lock (GIL) in .NET? (Trick Question)
  • .NET does *not* have a Global Interpreter Lock like Python. The CLR is designed for true multithreading, allowing multiple threads to execute managed code concurrently on multiple CPU cores.
73. What is the Task Parallel Library (TPL)?
  • The TPL is a set of public types and APIs in the System.Threading.Tasks namespace that simplifies parallel programming. It provides constructs like Task, Parallel.For, and Parallel.ForEach to help manage parallel execution.
74. What is a deadlock?
  • A deadlock occurs when two or more threads are blocked indefinitely, waiting for each other to release resources (like locks) that they need to proceed.
75. What is a race condition?
  • A race condition occurs when the outcome of a program depends on the unpredictable timing of multiple threads accessing and modifying shared data. The results can vary depending on which thread gets access to the data first.
76. How can you prevent race conditions?
  • Using synchronization primitives like locks (lock keyword), mutexes, semaphores, or by using thread-safe data structures.
77. What is the purpose of the lock keyword?
  • The lock keyword is used to acquire an exclusive lock on an object for the duration of a block of code. Only one thread can hold the lock at a time, preventing other threads from executing the code within the locked block, thus protecting shared resources from race conditions.
78. What is the difference between IEnumerable and ICollection?
  • IEnumerable: Represents a sequence of elements that can be iterated. It provides basic iteration capabilities but no methods for adding, removing, or getting the count efficiently.
  • ICollection: Inherits from IEnumerable and adds methods for managing a collection, such as Add, Remove, Contains, and a Count property. It represents a collection that can be modified and queried for size.
79. What is the difference between ICollection and IList?
  • IList: Inherits from ICollection and adds methods for accessing elements by index (e.g., [] indexer), inserting, and removing elements at specific positions. It represents a collection that is ordered and can be accessed by index.
80. What is the purpose of the yield break statement?
  • yield break is used in an iterator block to stop the iteration and indicate that the end of the sequence has been reached.
81. What are nullable value types?
  • Nullable value types (e.g., int?, bool?) allow value types to represent their normal range of values, plus an additional null value. They are instances of the Nullable struct.
82. What is the null-conditional operator (?.)?
  • The null-conditional operator provides a concise way to access members (properties, methods) of an object only if the object is not null. If the object is null, the expression evaluates to null, preventing a NullReferenceException.
83. What is the null-coalescing operator (??)?
  • The null-coalescing operator provides a default value for a nullable type or a reference type if it is null. expression1 ?? expression2 returns expression1 if it's not null, otherwise it returns expression2.
84. What is the purpose of the sealed override combination?
  • Using sealed override in a derived class means that this specific override cannot be overridden by any further derived classes.
85. What is the difference between a shallow copy and a deep copy?
  • Shallow Copy: Creates a new object, but copies only the references to the nested objects. Both the original and the copied object will point to the same nested objects. Achieved using MemberwiseClone().
  • Deep Copy: Creates a new object and also creates new instances of all nested objects. The original and the copied object have completely independent copies of all data. Requires manual implementation or serialization/deserialization.
86. What is the purpose of the ToString() method?
  • The ToString() method is defined in the base Object class and is intended to return a string representation of the current object. It's often overridden in derived classes to provide a meaningful string representation.
87. What is the purpose of the Equals() method?
  • The Equals() method is defined in the base Object class and is intended to determine whether two object instances are equal. For reference types, the default implementation checks for reference equality. For value types, the default implementation checks for value equality. It's often overridden in custom types to provide specific equality logic.
88. What is the purpose of the GetHashCode() method?
  • The GetHashCode() method is defined in the base Object class and returns a hash code for the object. It's used by hash-based collections (like Dictionary, HashSet) for efficient storage and retrieval. If you override Equals(), you must also override GetHashCode() to ensure consistency (equal objects must have the same hash code).
89. What is the difference between == and Equals()?
  • == operator: For value types, it performs a value comparison. For reference types, the default implementation performs a reference comparison (checks if they point to the same object in memory). The operator can be overloaded for custom types.
  • Equals() method: For reference types, the default implementation performs a reference comparison. For value types, the default implementation performs a value comparison (using reflection, which can be slow). Can be overridden in custom types to perform value comparison for reference types.
90. What is the purpose of the sealed class?
  • A sealed class cannot be inherited by any other class. This is often used for security reasons or to prevent unintended modifications to the class's behavior.
91. What is the purpose of the abstract class?
  • An abstract class cannot be instantiated directly and is meant to be a base class for other classes. It can define common behavior and enforce that derived classes provide specific implementations for abstract members.
92. What is a Record in C#? (C# 9+)
  • A record is a reference type primarily intended for immutable data. It provides concise syntax for defining properties, and automatically generates methods like Equals, GetHashCode, ToString, and a copy constructor, focusing on value equality.
93. What is the difference between a class and a record?
  • Class: Reference type. Primarily for mutable data. Reference equality by default. Manual implementation of equality methods and copy constructors.
  • Record: Reference type (by default). Primarily for immutable data. Value equality by default. Compiler-synthesized members for equality and copying.
94. What are Indexers in C#?
  • Indexers allow instances of a class or struct to be indexed like an array (e.g., myObject[index]). They are defined using the this keyword and provide get and set accessors similar to properties.
95. What are Operator Overloads?
  • Operator overloading allows you to redefine the behavior of standard operators (like +, -, *, ==, !=) for your custom classes or structs. This makes working with instances of your types more intuitive.
96. What is the purpose of the const modifier on a method? (Trick Question)
  • The const modifier does not apply to methods in C#. It's used for fields. The concept of a "constant method" (one that doesn't modify the object's state) exists in languages like C++ but not directly in C#.
97. What is the purpose of the readonly modifier on a struct?
  • Applying readonly to a struct makes all its fields implicitly readonly. This ensures that instances of the struct are immutable.
98. What is the purpose of the in, ref, and out parameters?
  • in: Passes the argument by reference, but the method cannot modify the value of the parameter. Ensures the original variable is not changed.
  • ref: Passes the argument by reference. The method can read and modify the value of the parameter, and changes are reflected in the original variable. The variable must be initialized before being passed.
  • out: Passes the argument by reference. The method is required to assign a value to the parameter before returning. Useful for returning multiple values from a method. The variable does not need to be initialized before being passed.
99. What is the difference between ref and out?
  • ref: Requires the variable to be initialized before being passed to the method.
  • out: Does not require the variable to be initialized before being passed. The method *must* assign a value to the parameter before returning.
100. What is a nullable reference type? (C# 8+)
  • Nullable reference types are a feature introduced in C# 8 (and enabled by default in .NET 6+ project templates) that allows the compiler to perform static analysis to detect potential NullReferenceException issues. It distinguishes between reference types that are *intended* to be null (string?) and those that are *not* (string).
101. What is Pattern Matching in C#?
  • Pattern matching is a feature that allows you to test if an object has a certain shape (type, value, or properties) and, if it does, extract data from it. It's used with keywords like is, switch expressions, and property patterns.
102. What are Tuples in C#? (C# 7+)
  • Tuples provide a lightweight way to group multiple values into a single composite type without needing to define a separate class or struct. They are value types (for struct tuples) and can have named elements.
103. What is the difference between System.Tuple (old) and value tuples (new)?
  • System.Tuple: Reference type, immutable, elements accessed by Item1, Item2, etc. (not easily named), performance overhead.
  • Value Tuples (e.g., (int a, string b)): Value type (struct), mutable by default (can be made immutable with readonly), elements can be named, better performance. Recommended in modern C#.
104. What is the purpose of the using static directive? (C# 6+)
  • The using static directive allows you to import static members (methods, properties, fields) of a class directly into your code, so you can call them without prefixing the class name (e.g., WriteLine("Hello"); instead of System.Console.WriteLine("Hello");).
105. What are Default Interface Methods? (C# 8+)
  • Default interface methods allow you to provide an implementation for a method directly within an interface. This is useful for adding new members to existing interfaces without breaking existing implementations.
106. What are Init-only Setters? (C# 9+)
  • Init-only setters (init keyword for properties) allow properties to be set only during object initialization (when the object is created). After initialization, the property becomes immutable. Useful for creating immutable objects with object initializers.
107. What are Top-level Statements? (C# 9+)
  • Top-level statements allow you to write executable code directly in a .cs file without explicitly defining a Program class and a Main method. The compiler generates the boilerplate code behind the scenes. Only one file in a project can use top-level statements.
108. What is Minimal APIs in ASP.NET Core? (.NET 6+)
  • Minimal APIs provide a simplified way to build HTTP APIs in ASP.NET Core with minimal dependencies and configuration. They allow you to define API endpoints directly in the Program.cs file using lambda expressions and routing.
109. What is Blazor?
  • Blazor is a framework for building interactive client-side web UI with .NET (C#) instead of JavaScript. It can run in the browser via WebAssembly (Blazor WebAssembly) or on the server (Blazor Server).
110. What is the difference between Blazor Server and Blazor WebAssembly?
  • Blazor Server: UI is rendered on the server, and UI updates and event handling are communicated over a SignalR connection. Requires a persistent connection.
  • Blazor WebAssembly: The .NET runtime and application code are downloaded to the browser and executed directly in the browser using WebAssembly. No persistent connection needed after initial download.
111. What is the purpose of NuGet?
  • NuGet is the package manager for .NET. It allows developers to discover, install, and manage third-party libraries and tools (packages) in their .NET projects.
112. What is a NuGet package?
  • A NuGet package is a compressed file (.nupkg) containing compiled code (DLLs), metadata, and other assets required by a project.
113. What is the purpose of the .csproj file?
  • The .csproj file is the project file for a C# project. It's an XML file that defines project settings, references to NuGet packages, files included in the project, build configurations, and target frameworks.
114. What is the difference between .NET SDK, .NET Runtime, and .NET Host?
  • .NET SDK: Includes everything needed to build and run .NET applications (Runtime, BCL, CLI, compilers, build tools).
  • .NET Runtime: Includes everything needed to run .NET applications (CLR, BCL).
  • .NET Host: The native executable (e.g., dotnet.exe) that starts a .NET application. It's part of the Runtime.
115. What is cross-compilation in .NET? (Trick Question)
  • .NET does not perform traditional cross-compilation where you compile code for one architecture on a different architecture (though you can publish self-contained apps for specific runtimes). C# code is compiled into IL, which is then JIT-compiled to native code on the target machine. The SDK and runtime are available for different operating systems and architectures.
116. What is Ahead-Of-Time (AOT) Compilation in .NET?
  • AOT compilation is a technique where IL code is compiled to native machine code *before* runtime. This can improve startup time and reduce memory usage compared to JIT compilation. .NET supports AOT for specific scenarios (e.g., Blazor WebAssembly, .NET MAUI, Native AOT publishing).
117. What is Native AOT publishing? (.NET 7+)
  • Native AOT publishing allows you to compile your .NET application into a single, self-contained native executable that does not require the .NET Runtime to be installed on the target machine. This results in faster startup times and smaller deployment sizes but has some limitations (e.g., requires trimming, limits reflection).
118. What is Trimming in .NET?
  • Trimming is a build-time optimization that removes unused code from your application and its dependencies. This helps reduce the size of self-contained deployments and Native AOT executables.
119. What is Tiered Compilation?
  • Tiered compilation is a feature in the .NET JIT compiler where code is initially compiled quickly (Tier 0) for fast startup, and then frequently executed code is recompiled with more optimizations (Tier 1) for better sustained performance.
120. What are Span and ReadOnlySpan? (C# 7.2+)
  • Span and ReadOnlySpan are lightweight structs that provide a type-safe, memory-safe, and high-performance way to work with contiguous regions of memory, such as arrays, strings, or native memory, without incurring copying overhead.
121. What is the purpose of the using var statement? (C# 8+)
  • using var variable = new DisposableObject(); is a concise syntax for the using statement when declaring and disposing of a variable that implements IDisposable. The variable's scope is the current block.
122. What are Property Patterns? (C# 8+)
  • Property patterns are a pattern matching feature that allows you to match on the properties of an object. For example: if (person is { Address: { City: "New York" } }).
123. What are Positional Patterns? (C# 8+)
  • Positional patterns are a pattern matching feature that allows you to match on the elements of a deconstructable type (like a record or a type with a Deconstruct method). For example: if (point is (0, 0)).
124. What is the purpose of the required modifier? (C# 11+)
  • The required modifier on a property or field indicates that it must be initialized by an object initializer when an instance of the containing type is created. The compiler enforces this.
125. What are Raw String Literals? (C# 11+)
  • Raw string literals allow you to define multi-line strings that can contain arbitrary characters (including quotes and backslashes) without needing escape sequences. They are enclosed in three or more double quotes (e.g., """...""").
126. What are Generic Attributes? (C# 10+)
  • Generic attributes allow you to use generic types as arguments to attributes (e.g., [MyAttribute]).
127. What is the purpose of the file access modifier? (C# 11+)
  • The file access modifier makes a type visible only within the source file in which it is declared. Useful for utility types that are only needed internally within a single file.
128. What is Parameter Null Checking? (C# 10+)
  • Using !! after a parameter name in a method signature (e.g., string name!!) allows the compiler to generate code to check if the parameter is null and throw an ArgumentNullException if it is. Provides a concise way to add null checks.
129. What are Global Usings? (.NET 6+)
  • Global usings (defined in the .csproj file or a dedicated .cs file with the global using keyword) allow you to define namespaces that are implicitly included in all code files within the project, reducing the need for repeated using directives.
130. What is Implicit Usings? (.NET 6+)
  • Implicit usings is a feature enabled by default in new .NET 6+ project templates that automatically includes a set of common namespaces (like System, System.Collections.Generic, System.Linq) based on the project SDK type (e.g., Microsoft.NET.Sdk.Web).
131. What is the difference between Global Usings and Implicit Usings?
  • Implicit usings are a *feature* that enables automatic inclusion of a predefined set of namespaces. Global usings are the *mechanism* (using the global using keyword or item in the .csproj) to define which namespaces are included globally. Implicit usings uses global usings behind the scenes.
132. What is the purpose of the IHttpClientFactory?
  • IHttpClientFactory is a factory for creating HttpClient instances in .NET Core/5+. It helps manage the lifetime of HttpClient, preventing issues like socket exhaustion, and allows for configuring and centralizing the creation of HttpClient instances with features like Polly integration for transient fault handling.
133. What is Razor Pages in ASP.NET Core?
  • Razor Pages are an alternative to the MVC pattern for building web UI in ASP.NET Core. They provide a page-centric model where the UI and the code-behind for a page are combined into a single file (.cshtml) or a pair of files (.cshtml and .cshtml.cs). Suitable for simpler scenarios.
134. What is the difference between MVC and Razor Pages?
  • MVC: Follows the Model-View-Controller pattern. Separates concerns into distinct Controller, View, and Model folders/classes. More suitable for complex applications with multiple controllers and shared components.
  • Razor Pages: Page-centric model. Code-behind is tightly coupled to the view. Simpler to get started for page-based scenarios.
135. What is gRPC in .NET?
  • gRPC is a high-performance, open-source framework for remote procedure calls (RPCs). It uses Protocol Buffers as its Interface Definition Language (IDL) and HTTP/2 for transport. .NET has excellent support for building gRPC services and clients.
136. What is SignalR in ASP.NET Core?
  • SignalR is a library for ASP.NET Core that simplifies adding real-time web functionality to applications. It enables server-side code to push content to connected clients instantly, supporting various transport methods like WebSockets.
137. What is the purpose of the [ApiController] attribute?
  • The [ApiController] attribute is applied to controllers in ASP.NET Core Web APIs. It enables several API-specific conventions and behaviors, such as automatic model validation, status code inference, and binding source inference.
138. What is Model Binding in ASP.NET Core?
  • Model binding is the process by which ASP.NET Core maps data from incoming HTTP requests (like form data, route values, query strings, request body) to parameters of action methods or properties of models.
139. What is Model Validation in ASP.NET Core?
  • Model validation is the process of checking if the data bound to a model meets specified rules (defined using data annotation attributes like [Required], [StringLength], etc.). If validation fails, the ModelState.IsValid property will be false.
140. What is the purpose of the IConfiguration interface?
  • IConfiguration is the interface used to access application configuration settings in ASP.NET Core/5+. It provides methods for reading configuration values from various registered sources.
141. What is the purpose of the appsettings.json file?
  • appsettings.json is a common file used in ASP.NET Core applications to store configuration settings in JSON format. It's a standard configuration source.
142. How do you handle different environments (Development, Staging, Production) in ASP.NET Core configuration?
  • ASP.NET Core supports environment-specific configuration files (e.g., appsettings.Development.json, appsettings.Production.json). Settings in environment-specific files override settings in the base appsettings.json. The active environment is determined by the ASPNETCORE_ENVIRONMENT environment variable.
143. What is In-Memory Database in EF Core?
  • The In-Memory database provider for EF Core allows you to use an in-memory database for testing or development purposes. It's not a real database and data is not persisted. Useful for unit and integration testing without needing a full database setup.
144. What is the purpose of the [FromRoute], [FromQuery], [FromBody] attributes?
  • These attributes (part of Model Binding) explicitly indicate where an action method parameter should be bound from:
    • [FromRoute]: From route values.
    • [FromQuery]: From query string parameters.
    • [FromBody]: From the request body (deserialized from JSON, XML, etc.).
145. What is the difference between Authentication and Authorization?
  • Authentication: Verifying the identity of a user (e.g., username/password, token). "Who are you?"
  • Authorization: Determining what an authenticated user is allowed to do. "What can you do?"
146. How is Authentication and Authorization handled in ASP.NET Core?
  • ASP.NET Core has built-in middleware and services for Authentication and Authorization. Authentication is typically configured using schemes (e.g., Cookie, JWT Bearer). Authorization is typically configured using policies and attributes like [Authorize].
147. What are Data Annotations?
  • Data Annotations are attributes (like [Required], [StringLength], [Range]) that you can apply to classes and properties to define metadata, often used for model validation in ASP.NET Core or for configuring EF Core entities.
148. What is the purpose of the BackgroundService class?
  • BackgroundService is a base class provided by .NET Core/5+ that simplifies implementing long-running background tasks in your application. It implements IHostedService and provides abstract methods (ExecuteAsync) for your background logic.
149. What is the purpose of IHostedService?
  • IHostedService is an interface that represents a service that is hosted within the application's host (IHost or IWebHost). Hosted services are started and stopped with the host, making them suitable for background tasks, scheduled jobs, or services that need to run continuously.
150. What is the purpose of the IHost builder? (.NET Core 3.1+)
  • The IHost builder is used to configure and build a generic host for .NET applications (console apps, background services, etc.). It provides a more general-purpose hosting model than IWebHost (used specifically for web apps).
151. What is the purpose of the IWebHost builder? (Older ASP.NET Core)
  • The IWebHost builder was used in older ASP.NET Core versions to configure and build the host for web applications. It's largely superseded by the IHost builder in modern .NET.
152. What is the difference between IHost and IWebHost?
  • IHost is a generic host suitable for any type of .NET application.
  • IWebHost is specifically for web applications and includes web-specific configurations and services. In modern .NET, IHost is typically used, and web-specific features are added via extensions.
153. What is the purpose of the AddControllers() and AddRazorPages() calls in Startup?
  • These methods (called on the IServiceCollection) register the necessary services (like MVC or Razor Pages services) with the Dependency Injection container, making them available for use in the application pipeline.
154. What is the purpose of the UseRouting() and UseEndpoints() middleware?
  • UseRouting(): Adds routing middleware to the pipeline. It matches incoming requests to endpoints based on defined routes.
  • UseEndpoints(): Adds endpoint middleware to the pipeline. It executes the endpoint that was selected by the routing middleware (e.g., executing a controller action, a Razor Page handler, or a Minimal API endpoint).
155. What is the purpose of the UseHttpsRedirection() middleware?
  • UseHttpsRedirection() middleware redirects HTTP requests to HTTPS.
156. What is the purpose of the UseStaticFiles() middleware?
  • UseStaticFiles() middleware enables serving static files (like HTML, CSS, JavaScript, images) from the web root directory (usually wwwroot).
157. What is the purpose of the UseAuthorization() and UseAuthentication() middleware?
  • UseAuthentication(): Adds the authentication middleware, which attempts to authenticate the user based on the configured authentication schemes.
  • UseAuthorization(): Adds the authorization middleware, which authorizes the user based on policies and requirements after they have been authenticated.
158. What is the difference between app.Use() and app.Run() in the middleware pipeline?
  • app.Use(middleware): Adds a middleware component to the pipeline. It can perform actions before and after the next middleware in the pipeline is called (by calling next()).
  • app.Run(middleware): Adds a terminal middleware component to the pipeline. It processes the request and typically does not call the next middleware. It short-circuits the pipeline.
159. What is the purpose of the Program.Main method? (Pre-C# 9)
  • The Program.Main method is the entry point of a console application. It's where the application execution begins. In modern .NET with top-level statements, this boilerplate is hidden.
160. What is the purpose of the ConfigureAwait(false) method?
  • ConfigureAwait(false) is used when awaiting a task (e.g., await someTask.ConfigureAwait(false);). It tells the runtime *not* to capture the current synchronization context (like the UI thread context in WPF/WinForms or the ASP.NET Core request context). This can improve performance and help prevent deadlocks in library code or non-UI applications. If you need to update UI elements or access request-specific state in ASP.NET Core after an await, you should omit ConfigureAwait(false).
161. What is the difference between synchronous and asynchronous programming?
  • Synchronous: Operations are executed sequentially. A thread waits for an operation to complete before moving to the next one. Can block the thread and make the application unresponsive during long-running operations.
  • Asynchronous: Operations can run concurrently without blocking the calling thread. The thread can perform other work while waiting for an asynchronous operation to complete. Uses constructs like async/await and Task.
162. What is the purpose of the CancellationToken?
  • A CancellationToken is used to signal that an asynchronous operation should be canceled. It's a cooperative cancellation model; the code performing the operation must periodically check if cancellation has been requested and stop gracefully if it has.
163. How do you handle errors in ASP.NET Core?
  • Using middleware like UseExceptionHandler (for production) or UseDeveloperExceptionPage (for development). You can also implement custom error handling middleware or use exception filters in MVC/API controllers.
164. What is the purpose of the Try-Catch-Finally block?
  • try: Contains code that might throw an exception.
  • catch: Contains code to handle a specific type of exception if one occurs in the try block.
  • finally: Contains code that is always executed, regardless of whether an exception occurred or was handled. Useful for cleanup operations.
165. What is the purpose of the async void method?
  • async void methods are typically used only for event handlers. They are "fire and forget" – the caller cannot await them or catch exceptions that occur within them. Using async Task for other asynchronous methods is generally preferred as it allows for proper error propagation and awaitability.
166. What is the difference between Task.Run() and Task.Factory.StartNew()?
  • Task.Run(): A convenience method for running CPU-bound work on the thread pool. It's the recommended way to start a new task for CPU-bound operations.
  • Task.Factory.StartNew(): A more general-purpose method for creating and starting tasks. It has more options but can be less intuitive and has some historical quirks. Task.Run() is often preferred unless you need specific advanced features of StartNew.
167. What is the purpose of the ConfigureAwait method? (Repeated, but important)
  • ConfigureAwait(continueOnCapturedContext: false): Prevents the continuation of the awaited task from being scheduled back on the original synchronization context. This can improve performance and prevent deadlocks in library code or non-UI scenarios.
  • ConfigureAwait(continueOnCapturedContext: true): (Default behavior) Ensures the continuation is scheduled back on the original synchronization context. Necessary for UI updates or accessing context-dependent resources (like HttpContext in older ASP.NET).