.NET
Part 1: C# Fundamentals & OOP
1. What is the difference between String and StringBuilder?
String is immutable, meaning every time you modify a string, a new object is created in memory, which can cause performance issues in loops. StringBuilder is mutable; it modifies the string data in the same memory location, making it much more efficient for heavy string manipulation.
2. What is the difference between an Abstract Class and an Interface? An interface only defines a contract (method signatures, properties) without implementation (though C# 8+ allows default implementations), and a class can implement multiple interfaces. An abstract class can have both abstract methods (no implementation) and concrete methods (with implementation), but a class can only inherit from one abstract class.
3. What is the difference between ref and out parameters?
Both allow passing variables by reference rather than by value. The difference is that a ref parameter must be initialized before it is passed to the method. An out parameter does not need to be initialized before passing, but the called method must assign a value to it before returning.
4. Explain IEnumerable vs. ICollection vs. IList.
IEnumerable: The base interface. It only allows forward-only iteration (usingforeach) and cannot modify the collection.ICollection: InheritsIEnumerable. Adds properties/methods likeCount,Add(), andRemove().IList: InheritsICollection. Adds indexer support, allowing you to access items by their index (e.g.,myList[2]).
5. What is the difference between virtual and abstract methods?
An abstract method has no implementation in the base class and must be overridden in the derived class. A virtual method provides a default implementation in the base class, which can be overridden in the derived class using the override keyword, but it is not mandatory.
Part 2: Async Programming & Multithreading
6. What is the difference between Task and Thread?
A Thread is an OS-level representation of an execution path; it is relatively heavy and expensive to create. A Task is a higher-level abstraction managed by the .NET Thread Pool. Tasks are lighter, return results (Task<T>), support cancellation, and work seamlessly with async/await.
7. What happens if you use .Result or Task.Wait() instead of await?
Using .Result or .Wait() blocks the calling thread until the task completes. In UI applications or ASP.NET (prior to Core), this easily causes deadlocks. await frees up the calling thread to do other work while the task finishes asynchronously.
8. What is Task.WhenAll vs. Task.WaitAll?
Task.WhenAll: Returns a single task that is complete when all supplied tasks have completed. It is used withawaitand does not block the thread.Task.WaitAll: A synchronous method that blocks the current thread until all supplied tasks are finished.
9. How do you cancel an asynchronous task in .NET?
You use a CancellationToken. You create a CancellationTokenSource, pass its Token into your async methods, and check token.ThrowIfCancellationRequested() within your asynchronous work loop.
10. What does ConfigureAwait(false) do?
By default, when an await finishes, it tries to resume execution on the original context (like the UI thread). ConfigureAwait(false) tells the compiler that it does not need to resume on the original context, allowing it to continue on any thread-pool thread. This prevents deadlocks and improves performance in library code.
Part 3: ASP.NET Core & Web API
11. What is Kestrel? Kestrel is the cross-platform, lightweight, default web server for ASP.NET Core. It is typically used as an edge server or placed behind a reverse proxy like IIS or Nginx for better security, load balancing, and request routing.
12. What are Filters in ASP.NET Core? Filters allow you to run custom code before or after specific stages in the request processing pipeline. Common types include:
- Authorization Filters: Run first to check if the user is authorized.
- Action Filters: Run immediately before and after a controller action executes.
- Exception Filters: Catch unhandled exceptions globally.
13. Attribute Routing vs. Conventional Routing?
Conventional routing is defined globally in Program.cs (e.g., {controller}/{action}/{id}). Attribute routing uses attributes directly on the controller and action methods (e.g., [Route("api/users/{id}")]). Web APIs almost exclusively use Attribute routing for more precise RESTful URI control.
14. How do you secure a .NET Web API?
The most common approach for modern APIs is using JWT (JSON Web Tokens). The client authenticates and receives a JWT, which it sends in the Authorization: Bearer <token> header of subsequent requests. The API validates the token's signature and expiration using ASP.NET Core authentication middleware.
15. What is the difference between IHostedService and BackgroundService?
IHostedService is an interface used to run background tasks in ASP.NET Core. BackgroundService is a base class that implements IHostedService and simplifies the process by providing an abstract ExecuteAsync method where you can write your long-running loop.
Part 4: Entity Framework Core
16. Explain Eager Loading, Lazy Loading, and Explicit Loading.
- Eager Loading: Loads related entities at the same time as the main entity using
.Include(). Creates one large SQL JOIN query. - Lazy Loading: Delays loading related data until the property is specifically accessed. It requires proxy classes and can lead to the "N+1 query problem" (executing many small database calls).
- Explicit Loading: Loads related data on demand using
_context.Entry().Collection().Load().
17. What are Tracking vs. No-Tracking queries?
By default, EF Core tracks changes to entities it retrieves so that calling SaveChanges() updates the database. If you only need read-only data (like displaying a list on a webpage), using .AsNoTracking() disables this tracking mechanism, significantly improving performance and reducing memory usage.
18. What are EF Core Migrations? Migrations are a way to keep your database schema in sync with your C# model classes. When you change a class (e.g., add a new property), you create a migration, which generates the SQL required to update the actual database tables to match your new code structure.
19. How do you prevent SQL Injection in EF Core?
EF Core automatically uses parameterized queries for LINQ statements, which inherently protects against SQL injection. If you must write raw SQL, you should use string interpolation with FromSqlInterpolated or pass DbParameter objects to FromSqlRaw. Never concatenate strings directly into a raw SQL query.
20. What is the difference between DbContext and DbSet?
DbContext: Represents the session with the database. It manages the database connection, transactions, and saves changes.DbSet<T>: Represents a specific table (or collection) within that database context. You use it to query and save instances of a specific entity (e.g.,DbSet<User> Users).