.Net Interview Preparation
.NET Framework / Core
Common Language Runtime (CLR):
1. What is CLR and how does it work in .NET applications?
The Common Language Runtime (CLR) is the core component of the .NET framework, responsible for managing the execution of .NET applications. It provides various services such as memory management, security enforcement, exception handling, and thread management.
How it works:
Compilation: When you write a .NET application, it gets compiled into an intermediate language (IL), not machine code. This makes the code platform-independent.
Execution by CLR: When the application is executed, the CLR’s Just-In-Time (JIT) compiler translates the IL code into native machine code specific to the underlying hardware.
Runtime Services: CLR also provides services like garbage collection (automatic memory management), exception handling, and security checks during execution.
2. How does the CLR manage memory?
CLR manages memory via the Garbage Collector (GC), which automates the process of allocating and releasing memory in .NET applications.
3. How does CLR manage exception handling?
CLR provides a structured approach to handle runtime exceptions via the Common Type System (CTS).
Exception Classes: In .NET, exceptions are represented as objects derived from the base System.Exception class.
Try-Catch-Finally: CLR supports structured exception handling using the try, catch, and finally blocks, which allow developers to handle exceptions gracefully and execute cleanup code.
Stack Unwinding: When an exception occurs, CLR looks up the call stack for matching catch blocks to handle the exception, a process known as stack unwinding.
4. What is Just-In-Time (JIT) compilation in CLR?
JIT compilation is the process of converting the intermediate language (IL) into native machine code that is specific to the target machine.
5. What are Assemblies and how do they relate to CLR?
Assemblies are the building blocks of .NET applications and contain the compiled code (IL), metadata, and resources for execution.
Role of CLR with Assemblies: The CLR loads assemblies into memory, verifies the code’s security, and ensures version compatibility before executing it.
6. What is Code Access Security (CAS) in CLR?
CAS is a security model in .NET that determines whether code has the necessary permissions to perform certain operations based on its origin and other identity factors.
Security Enforcement: CLR enforces security policies based on the code’s trust level, limiting access to sensitive system resources or operations unless the necessary permissions are granted.
7. How does the CLR handle threading?
CLR provides a managed threading environment that allows for multi-threading within .NET applications.
Thread Pooling: CLR optimizes thread creation by maintaining a pool of worker threads that can be reused for tasks, reducing overhead.
Concurrency: The CLR’s thread scheduler manages execution, allowing for multi-core or multi-processor systems to handle parallelism efficiently.
Garbage Collection:
1. How does the garbage collector work in .NET?
The Garbage Collector (GC) in .NET is a part of the runtime environment that automates memory management. Its primary purpose is to reclaim memory used by objects that are no longer needed, thus preventing memory leaks and optimizing memory usage.
Memory Allocation: When a .NET application creates objects, the memory for these objects is allocated on the managed heap.
Tracking References: The GC tracks references to objects. When objects are no longer referenced by any part of the application (i.e., they become unreachable), they are eligible for garbage collection.
Reclaiming Memory: The GC identifies and collects these unreachable objects, reclaims their memory, and compacts the heap to reduce fragmentation, making the memory available for new allocations.
2. Can you explain the different phases of garbage collection?
Garbage collection in .NET involves several phases, each designed to ensure efficient and effective cleanup of memory.
Mark Phase: In this phase, the GC identifies which objects are still in use (reachable) by tracing references from root objects such as local variables and static fields. This phase marks all reachable objects.
Sweep Phase: During this phase, the GC scans the heap to identify and remove objects that were not marked in the previous phase (i.e., unreachable objects). These objects are collected and their memory is reclaimed.
Compact Phase: After sweeping, the GC may move the surviving objects closer together to reduce fragmentation. This phase helps to ensure that memory is contiguous, improving allocation performance.
3. What are Generations in garbage collection?
The concept of Generations helps the GC optimize performance by dividing objects into different groups based on their age.
Generation 0: This is where newly allocated objects are placed. The GC frequently collects objects in Gen 0 because many objects are short-lived.
Generation 1: Objects that survive a Gen 0 collection are moved to Gen 1. The GC performs less frequent collections on Gen 1 compared to Gen 0.
Generation 2: Objects that survive multiple collections are eventually moved to Gen 2. Gen 2 is collected less frequently because it is expected that these objects have a longer lifetime.
The GC periodically checks for objects that are no longer referenced by the application and reclaims that memory, making it available for new allocations. Generational Garbage Collector focuses on collecting objects in Gen 0 and Gen 1 first, as they tend to be short-lived, reducing overhead.
4. What are Large Object Heaps (LOH) and how does the GC handle them?
The Large Object Heap (LOH) is a separate part of the managed heap for objects that are larger than 85,000 bytes. These objects are not moved during garbage collection to avoid the overhead of relocating large objects.
LOH Collection: The LOH is collected as part of Gen 2 garbage collection. Since LOH is collected less frequently, this can lead to memory fragmentation if large objects are frequently allocated and deallocated.
5. What are the impacts of Garbage Collection on application performance?
Garbage collection can impact performance in several ways:
Pause Time: The GC introduces pauses in application execution while it performs collection, which can affect application responsiveness.
Throughput: Frequent collections can reduce throughput, as the application spends more time managing memory.
Latency: Applications with high latency requirements may need to optimize GC settings or use low-latency garbage collection modes to minimize pause times.
6. How can you tune garbage collection for performance in .NET?
Several techniques can be used to optimize garbage collection performance:
GC Settings: Configure GC settings in the .NET configuration file or use runtime configuration options to adjust GC behavior based on application needs.
Memory Profiling: Use memory profiling tools to analyze object allocations and identify memory issues.
Reduce Allocations: Minimize object allocations and deallocations to reduce the frequency of GC pauses.
7. What is GC latency mode and how does it affect garbage collection?
GC Latency Mode allows you to adjust the behavior of the garbage collector to balance between throughput and responsiveness:
Interactive: Optimizes for low latency and responsiveness, suitable for applications with stringent performance requirements.
Batch: Optimizes for throughput and overall performance, suitable for background or server applications where responsiveness is less critical.
8. How does GC handle finalization in .NET?
Finalization is the process of cleaning up resources before an object is collected. In .NET, this is typically handled using finalizers:
Finalizers: Methods defined using the ~ClassName syntax that are called by the GC before the object’s memory is reclaimed.
Dispose Pattern: The recommended approach for managing resources is to implement the IDisposable interface and use the Dispose method to release resources explicitly, avoiding reliance on finalizers for critical cleanup.
Threading and Task:
1. Explain the concept of threading in .NET.
Threading in .NET allows an application to perform multiple tasks simultaneously. It involves creating and managing individual threads within a process, where each thread can execute independently of others. Threads in .NET share the same memory space but run their own execution paths.
Single-threading: The application has only one thread, which runs all tasks sequentially.
Multithreading: The application has multiple threads that run in parallel, allowing for concurrent execution of tasks.
2. What is the difference between Process and Thread?
Process:
A process is an instance of a running application.
It has its own memory space and resources, such as file handles and network connections.
Communication between processes is more expensive because they operate in isolated memory spaces (inter-process communication required).
Thread:
A thread is the smallest unit of execution within a process.
Threads within the same process share memory and resources.
Communication between threads is faster since they share the same memory, but synchronization is required to avoid issues like race conditions.
3. What is the difference between a Task and a Thread in .NET?
Thread: A thread is the basic unit of execution within a process. Each thread runs code and can perform tasks independently of other threads. When a new thread is created, the operating system allocates resources for it (like memory, CPU time, etc.), which can be expensive. Thread management (creating, starting, joining, and destroying threads) is manual in traditional threading models.
Task: A Task in .NET represents an asynchronous operation and is part of the Task Parallel Library (TPL). It provides a higher-level abstraction for managing and executing work. Task is easier to use and more efficient for asynchronous programming because the framework handles many details like pooling, context switching, and load balancing.
Tasks are typically used for I/O-bound or CPU-bound work.
The TPL manages the thread pool for tasks, making it more efficient than creating and managing threads manually.
4. Explain Multithreading
Multithreading refers to the ability of a CPU, or a single core in a multi-core processor, to execute multiple threads concurrently. In .NET, multithreading allows you to run multiple tasks in parallel, improving application performance, particularly for tasks that can be performed independently.
Key concepts:
Concurrency: Multiple threads are executed seemingly at the same time.
Parallelism: Actual simultaneous execution of threads on multiple processors.
Synchronization: Mechanisms like lock, Mutex, Semaphore, etc., are used to ensure that multiple threads don't interfere with each other.
Multithreading is useful in scenarios such as:
Running multiple independent tasks (e.g., file download, processing in the background).
Improving responsiveness of UI applications by offloading work to background threads.
5. How do you manage multithreading in .NET applications?
Thread Class: You can create threads using the Thread class and manually start them using Start().
ThreadPool: Threads can be pooled and reused using the .NET ThreadPool, which reduces the overhead of creating and destroying threads.
Task Parallel Library (TPL): The TPL simplifies multithreading by abstracting tasks. Instead of manually creating threads, you create and run tasks (Task.Run), and the TPL manages the underlying threads.
async/await: These keywords are used for asynchronous programming, making multithreading easier to manage by allowing methods to run asynchronously without blocking the main thread.
Locks and Synchronization: Techniques such as locks (lock keyword), Monitor, Mutex, Semaphore, and ReaderWriterLock are used to prevent race conditions and ensure thread safety.
6. What is a ThreadPool in .NET
The ThreadPool is a collection of threads that can be reused for different tasks, reducing the overhead of creating and destroying threads.
Threads in the pool are reused for multiple tasks, improving performance.
You can queue tasks to the ThreadPool using ThreadPool.QueueUserWorkItem() or by using the Task Parallel Library (Task.Run()).
The ThreadPool automatically manages the number of threads based on the system load.
7. What is a Task Parallel Library (TPL)
The Task Parallel Library (TPL) is a set of APIs that simplifies parallel programming by abstracting the complexity of threading. It provides efficient and scalable execution of tasks in parallel.
Task Class: Represents an asynchronous operation that can be awaited or continued.
Parallel Class: Allows parallel execution of loops and tasks, such as Parallel.For and Parallel.ForEach.
Data Parallelism: Enables concurrent execution of tasks that work on a collection of data.
Task Continuations: Allows you to specify what happens after a task completes using ContinueWith().
8. What is async and await in .NET
async and await are key keywords for asynchronous programming in .NET, used to make code non-blocking and responsive.
async: Marks a method as asynchronous, indicating it contains code that may run asynchronously.
await: Suspends the execution of an async method until the awaited task is complete. It doesn’t block the current thread while waiting for the result.
Example:
public async Task<string> FetchDataAsync()
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("https://example.com");
return result;
}
async/await is commonly used with I/O-bound operations, such as file access or network requests, to avoid blocking the main thread.
9. What are thread-safe collections in .NET?
ConcurrentBag, ConcurrentDictionary, BlockingCollection, etc., are thread-safe collections in .NET that allow multiple threads to access them concurrently without the need for explicit locking.
10. Explain the lock keyword in C# and its importance in multithreading.
The lock keyword is used to prevent multiple threads from simultaneously executing a block of code, ensuring thread safety.
11. What is a deadlock and how can it be avoided in multithreading?
A deadlock occurs when two or more threads are blocked forever, each waiting on the other to release a resource. It can be avoided by using proper synchronization mechanisms like Monitor.TryEnter, acquiring locks in the same order, and using timeout for locks.
Async/Await:
10. How does async/await work in .NET?
11. Can you give an example of asynchronous programming?
12. What is the role of Async and Await?
Memory Management:
13. How do you manage memory in .NET applications?
14. What are Large Object Heaps (LOH), Dispose Pattern, and Finalizers?
15. What is the difference between “Dispose” and “Finalize”?
16. What is the difference between “Finalize” and “Finally” methods?
17. Can we force Garbage Collector to run?
Reflection:
18. What is Reflection in .NET, and how is it used?
19. What’s the difference between Reflection and Dynamic in C#?
Dependency Injection:
20. What is Dependency Injection, and why is it used?
21. What are the differences between AddSingleton, AddScoped, and AddTransient in .NET Core?
22. How to implement Dependency Injection in .NET Core?
23. What are the advantages of Dependency Injection in .NET Core?
Entity Framework (EF):
24. What is Entity Framework, and how does it differ from ADO.NET?
25. Explain code-first migration in Entity Framework.
26. What are DbContext and DbSet in EF?
27. How Entity Framework works? OR How to setup EF?
28. What is meant by DBContext and DBSet?
29. What are the different types of development approaches used with EF?
30. What is the difference between LINQ to SQL and Entity Framework?
SOLID Principles:
31. Can you explain the SOLID principles in the context of .NET development?
Factory Design Pattern:
32. Explain the factory design pattern with an example in C#.
33. What’s the difference between a Factory Method and an Abstract Factory?
Middleware:
34. What is middleware in ASP.NET Core?
35. How would you implement custom middleware to handle exceptions or logging?
36. What’s the difference between filters and middleware?
Difference between .NET Core and .NET Framework:
37. How do .NET Core and .NET Framework differ in terms of architecture and features?