Friday, February 7, 2025

.NET Core interview questions and answers

for an experienced developer:


1. What are the differences between .NET Core and .NET Framework?

Answer:

  • Platform: .NET Core is cross-platform, meaning it can run on Windows, Linux, and macOS. .NET Framework, on the other hand, is only for Windows.
  • Performance: .NET Core is optimized for performance and is faster compared to the .NET Framework.
  • Deployment: .NET Core supports side-by-side installation, meaning multiple versions can be installed on the same machine, while .NET Framework requires a single version per machine.
  • Open Source: .NET Core is open source, while .NET Framework is closed source.
  • Versioning: .NET Core uses a more modular approach with NuGet packages, while .NET Framework is monolithic.

2. What is Dependency Injection (DI) in .NET Core?

Answer: Dependency Injection is a design pattern used to implement IoC (Inversion of Control). In .NET Core, DI is built-in and allows objects to be passed (injected) into classes that depend on them. This promotes loose coupling and makes testing easier.

Example:

csharp

// 1. Interface public interface INotificationService { void Notify(string message); } // 2. Implementation public class EmailNotificationService : INotificationService { public void Notify(string message) { Console.WriteLine("Sending Email: " + message); } } // 3. Configure DI in Startup.cs public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddScoped<INotificationService, EmailNotificationService>(); } } // 4. Controller using DI public class HomeController : Controller { private readonly INotificationService _notificationService; public HomeController(INotificationService notificationService) { _notificationService = notificationService; } public IActionResult Index() { _notificationService.Notify("Hello World!"); return View(); } }

3. What are middleware components in .NET Core?

Answer: Middleware components in .NET Core are pieces of code that are executed on each HTTP request. They are used to handle requests, responses, authentication, logging, error handling, and more. Middleware components are executed in the order they are added in the Configure method in Startup.cs.

Example:

csharp

public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); // Middleware for dev exception page } app.UseStaticFiles(); // Middleware for serving static files app.UseRouting(); // Middleware to route requests to appropriate controllers app.UseEndpoints(endpoints => { endpoints.MapControllers(); // Map controllers to endpoints }); } }

4. Explain Entity Framework Core and its advantages.

Answer: Entity Framework (EF) Core is an ORM (Object-Relational Mapping) framework for .NET Core that allows developers to interact with a database using .NET objects. It simplifies data access, eliminates the need for raw SQL queries, and provides features like LINQ, migrations, and change tracking.

Advantages:

  • Cross-platform: EF Core works on Windows, Linux, and macOS.
  • Performance: EF Core is more lightweight and performs better compared to EF 6 in many scenarios.
  • Migrations: EF Core has a migration feature to handle database schema changes.
  • LINQ Support: EF Core allows querying using LINQ, which is type-safe and easier to maintain.

Example:

csharp

// Define a model class public class Student { public int StudentId { get; set; } public string Name { get; set; } } // Define a DbContext public class SchoolContext : DbContext { public DbSet<Student> Students { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer("YourConnectionStringHere"); } // Performing a query using LINQ using (var context = new SchoolContext()) { var students = context.Students.Where(s => s.Name.StartsWith("J")).ToList(); }

5. What is the difference between IActionResult and ActionResult in ASP.NET Core MVC?

Answer:

  • IActionResult is an interface that represents the result of an action method. It allows you to return different types of responses like JSON, views, or status codes.
  • ActionResult is a concrete class that implements IActionResult and is used in controllers. It allows you to return specific result types, such as ViewResult, JsonResult, RedirectResult, etc.

Example:

csharp

// IActionResult example public IActionResult Index() { return View(); // ViewResult implements IActionResult } // ActionResult example public ActionResult<int> Add(int a, int b) { return Ok(a + b); // ActionResult<T> can return a specific type, like int. }

6. What is Kestrel in ASP.NET Core?

Answer: Kestrel is the default cross-platform web server used in ASP.NET Core. It's lightweight, fast, and designed to handle HTTP requests in a high-performance manner. Kestrel is usually run behind a reverse proxy like IIS or Nginx in production environments.

Example: In the Program.cs file, the Kestrel server is configured by default:

csharp
public class Program
{ public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseKestrel() // Default Kestrel server .UseStartup<Startup>(); }); }

7. What are async/await and how are they used in .NET Core?

Answer: async and await are used to implement asynchronous programming in C#. async marks a method as asynchronous, and await is used to wait for a Task to complete without blocking the thread.

Example:

csharp

public class MyService { public async Task<string> GetDataAsync() { await Task.Delay(2000); // Simulate async task return "Data fetched!"; } }

In the controller:

csharp

public class HomeController : Controller { private readonly MyService _service; public HomeController(MyService service) { _service = service; } public async Task<IActionResult> Index() { string data = await _service.GetDataAsync(); return Content(data); } }

8. What is the appsettings.json file in .NET Core?

Answer: appsettings.json is a configuration file in .NET Core used to store application settings, such as connection strings, logging settings, or other configuration data. It allows for flexible configuration management without modifying code.

Example:

{
"AppSettings": { "ApiKey": "your-api-key", "BaseUrl": "https://example.com" } }

In Startup.cs:

public void ConfigureServices(IServiceCollection services)
{ var apiKey = Configuration["AppSettings:ApiKey"]; services.AddSingleton(new ApiService(apiKey)); }