Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Top 50 .NET Core Interview Questions and Answers 2025

Top 50 .NET Core Interview Questions and Answers 2025

06 Jun 2024
Question
52.9K Views
52 min read
Learn with an interactive course and practical hands-on labs

.NET Course

.NET Core Interview Questions: An Overview

Are you a .NET enthusiast? Do you want to take a step further in the .NET developer roadmap? If yes, you have come to the right place. In this .NET Core tutorial on .NET Core Interview Questions, we have tried our best to provide you with some of the top .NET Core Interview Questions and Answers. After going through these questions, you can check your knowledge through our .NET Core Certification Training

Basic .NET Core Interview Questions for Freshers

1. What do you understand by .NET Core Framework?

  • .NET Core is a cross-platform, open-source framework that is the successor of .NET for building various types of applications, including web, desktop, and console applications.
  • It provides runtime, libraries, and development tools for building and running .NET applications on different platforms.
  • .NET Core supports multiple programming languages, including C#, F#, and Visual Basic.

2. State some important characteristics of .NET Core.

  • Cross-Platform Compatibility: .NET Core is designed to be cross-platform, allowing developers to build and run applications on various operating systems such as Windows, Linux, and macOS.
  • Open-Source: .NET Core is an open-source framework, with its source code available on GitHub. This openness encourages community contributions, fosters transparency, and enables developers to explore and understand the inner workings of the framework.
  • Modular Architecture: .NET Core follows a modular architecture, where features are organized into separate packages (NuGet packages).
  • High Performance: .NET Core is optimized for performance, with features such as just-in-time (JIT) compilation, runtime optimizations, and support for asynchronous programming patterns.
  • Side-by-Side Versioning: .NET Core supports side-by-side versioning, allowing multiple versions of the runtime and framework to be installed on the same machine.
  • Cloud-Native Support: .NET Core is well-suited for cloud-native development, with support for microservices architecture, containerization (e.g., Docker), and cloud platforms such as Microsoft Azure.
  • Modern Language Features: .NET Core supports modern language features and programming paradigms, including asynchronous programming with async/await, functional programming concepts, language enhancements (e.g., pattern matching, nullable reference types in C# 8.0), and more.
  • Tooling and Ecosystem: .NET Core comes with a rich set of development tools, including the cross-platform .NET CLI (Command-Line Interface), Visual Studio IDE (Integrated Development Environment), Visual Studio Code, and various third-party tools and extensions.

3. Differentiate between .NET and .NET Core.

Features.NET Core.NET framework
CompatibilityIt works based on the principle of “build once, run anywhere”. It is cross-platform, so it is compatible with different operating systems such as Linux, Windows, and Mac OS.This framework is compatible with the Windows operating system only. Even though, it was developed to support software and applications on all operating systems.
InstallationSince it is cross-platform, it is packaged and installed independently of the OS.It is installed in the form of a single package for Windows OS.
Application ModelsIt does not support developing the desktop application and it focuses mainly on the Windows mobile, web, and Windows store.It is used for developing both desktop and web applications, along with this it also supports Windows Forms and WPF applications.
Performance and ScalabilityIt provides high performance and scalability.It is less effective compared to .Net Core in terms of performance as well as scalability of applications.
Support for Micro-Services and REST ServicesIt supports developing and implementing the micro-services and the user is required to create a REST API for its implementation.It does not support the microservices’ development and implementation, but it supports REST API services.
Packaging and ShippingIt is shipped as a collection of Nugget packages.All the libraries that belong to the .Net Framework are packaged and shipped all at once.
Android DevelopmentIt is compatible with open-source mobile app platforms like Xamarin, via .NET Standard Library. Developers can make use of tools of Xamarin for configuring the mobile application for particular mobile devices like Android, iOS, and Windows phones.It does not support the development of mobile applications.
CLI ToolsFor all supported platforms, it provides lightweight editors along with command-line tools..NET is heavy for CLI(Command Line Interface) and developers usually prefer to work on the lightweight CLI.
Deployment ModelThe updated version of the .NET Core gets initiated on one machine at a time, which means it gets updated in new folders/directories in the existing application without affecting it. Thus, we can say that .NET Core has a very good flexible deployment model.When the updated version is released, it is deployed only on the Internet Information Server at first.

4. What is CoreCLR?

The CLR is the execution/ run-time engine in .NET Core, that is, it is responsible for the execution and running of programs in different programming languages. It consists of the following major components:

 CoreCLR in .net core

  • Garbage collector
  • JIT compiler
  • Low-level classes
  • Primitive data types
  • CLS and CTS

The Common Language Runtime (CLR) performs the garbage collection and code compilation functions etc.

5. What is Kestrel?

Kestrel is an event-driven, I/O-based, open-source, cross-platform, and asynchronous server that hosts .NET applications. It is provided as a default server for .NET Core therefore, it is compatible with all the platforms and their versions that .NET Core supports.

Kestrel in .net core

Kestrel supports both HTTP/1.x and HTTP/2 protocols, providing flexibility and performance improvements for modern web applications.

6. Describe the components of .NET Core.

  1. Common Language Runtime (CLR): It is the runtime environment that manages the execution of .NET Core applications. It provides features such as memory management, exception handling, garbage collection, and type safety.
  2. Base Class Library (BCL): It is a collection of reusable classes, types, and APIs that provide fundamental functionality for building .NET Core applications.
  3. CoreFX: CoreFX is a foundational set of libraries that complement the Base Class Library and provide additional functionality for building .NET Core applications.
  4. ASP.NET Core: It is a cross-platform web framework for building modern web applications and services. It includes features for building web APIs, MVC web applications, real-time web applications using SignalR, and more.
  5. Entity Framework Core: It is an object-relational mapping (ORM) framework that enables developers to work with databases using .NET objects. It provides a powerful set of APIs for querying, updating, and managing database data using .NET Core applications.
  6. CLI (Command-Line Interface): The .NET Core CLI provides a command-line interface for creating, building, running, and managing .NET Core applications.
  7. .NET Standard: .NET Standard is a formal specification that defines a set of APIs that must be available on all .NET implementations, including .NET Core, .NET Framework, and Xamarin.
  8. Tooling: .NET Core includes a set of development tools, including Visual Studio, Visual Studio Code, and various command-line tools, that help developers build, debug, and deploy .NET Core applications efficiently.

7. What are NuGet packages?

NuGet packages are parts of the package management system for .NET which are essential to carry on any development on the platform. These packages contain libraries and other descriptive metadata and are managed by NuGet.

In other words, a NuGet package is a single zip file with a .nupkg extension. The file contains compiled codes, files related to the code, and descriptions. Developers can create and share these packages by publishing them to either private or public hosts. They can also use the packages available and add to projects on an as-needed basis.

8. Is Garbage collection an ongoing process? When does it occur?

Yes, garbage collection (GC) is an ongoing process in managed memory environments like those provided by .NET. It occurs automatically in the background to reclaim memory occupied by objects no longer used by the application, thus freeing up memory for future allocations.

Garbage collection can occur at different times, including:

  1. During memory allocation: When an application requests memory allocation and the system detects insufficient memory, it may trigger a garbage collection cycle to free up memory before allocating more.
  2. When a certain threshold is reached: The garbage collector monitors memory usage and triggers a collection when certain thresholds, such as generation sizes or memory pressure, are met or exceeded.
  3. Explicitly: Developers can request garbage collection explicitly by calling GC.Collect() method. However, this is typically not recommended in most scenarios because the garbage collector is usually efficient at managing memory automatically.
  4. During idle periods or low system activity: The garbage collector may take advantage of idle periods or low system activity to perform more intensive garbage collection cycles without impacting application performance.

9. State the differences between .Net Core and Mono.

differences between .Net Core and Mono

Parameters.Net CoreMono
DefinitionA part of .NET framework which is specially optimized for designing modern apps and supporting developer workflowsIt is also part of .NET family frameworks, but this framework is optimized for iOS, macOS, Android, and Windows devices by the Xamarin platform
Best application Area To design command line applications web application development, Designing background service apps, Desktop applicationMobile app development, Designing games, Code compilation within the browser, Designing multi-platform desktop applications
Specific featuresNatural acquisition Modular framework Smaller deployment footprint Fast release cyclesNative User Interface Native API Access Native Performance Productivity
App ModelsUWP (Universal Windows Platform), ASP.NET CoreXamarin iOS, Xamarin Android, Xamarin Forms, Xamarin Mac
Base libraryCoreFX Class LibraryMono Class Library

10. What are service lifetimes in .NET Core?

In .NET Core, service lifetimes define how long instances of services managed by the built-in dependency injection container (DI container) should live within the application. The choice of service lifetime affects how instances are created, reused, and disposed of by the DI container.

There are three types of service lifetimes supported by .NET Core:

 service lifetimes in .NET Core

To specify the service lifetime when registering services with the DI container in .NET Core, you use the appropriate extension methods:

  • AddTransient: Registers a transient service.
  • AddScoped: Registers a scoped service.
  • AddSingleton: Registers a singleton service.

services.AddTransient<imytransientservice, mytransientservice="">();
services.AddScoped<imyscopedservice, myscopedservice="">();
services.AddSingleton<imysingletonservice, mysingletonservice="">();

11. What is meant by Razor Pages?

Razor Pages is a comparatively newer and more simplified web app development/ programming model. The Razor Pages follow a file-based routing approach thus simplifying the "Model-View-Controller" architectural model of ASP.NET. The code and the HTML are both in a single file which eliminates the need for separate view models, controllers, action methods, etc.

 Razor Pages

Example

Suppose you have a Razor Page named Index.cshtml located in the Pages directory of your ASP.NET Core project. This page will display a greeting message to the user.


@page
@model IndexModel
<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to My Razor Page!</h1>
    <p>@Model.GreetingMessage</p>
</body>
</html>

using Microsoft.AspNetCore.Mvc.RazorPages;

public class IndexModel : PageModel
{
    public string GreetingMessage { get; set; }

    public void OnGet()
    {
        // Set the greeting message
        GreetingMessage = "Hello, World!";
    }
}
  • The Index.cshtml file represents the Razor Page itself. It contains HTML markup along with Razor syntax, such as @page and @model, to define the page and its associated model.
  • The Index.cshtml.cs file is the code-behind file for the Razor Page. It contains the C# code that defines the behavior and logic for the page. In this case, it's a PageModel class with a property GreetingMessage and a method OnGet() that sets the greeting message.

12. What are Empty migrations?

When you want to add migrations without making any changes in the model it might lead to the creation of code files with empty classes. These can be customized to perform operations not related to the core Entity Framework (EF) model.

13. What do you know about .NET Core middleware?

A middleware is a component of an application pipeline that handles requests and responses. That is, the middleware component chooses whether or not to pass an incoming request to the next component of the pipeline. It is also responsible for giving responses or processing the request before and after it passes the pipeline.

The below diagram shows a middleware request pipeline consisting of many delegates called one after another. Where black arrows mark the direction of execution. Each delegate in the diagram performs some operations before or after the next delegate.

.NET Core middleware

14. What languages can you use on .NET Core?

Developers can use multiple programming languages including C++, C#, F#, Visual Basic, etc to work in the framework and develop .NET Core applications. The Microsoft Intermediate Language (MSIL) and Common Language Infrastructure (CLI) make it possible to transform any programming language into CPU-independent instructions.

15. Are ASP.NET Core and .NET Framework compatible?

Yes, ASP.NET Core works with both the .NET framework and the .NET Core framework and is managed by Microsoft.

16. Explain the concept of dependency injection in .NET Core. How does it differ from other dependency injection frameworks you have used?

Dependency injection (DI) in .NET Core is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. It promotes loose coupling, testability, and maintainability by allowing the runtime to provide required dependencies instead of hardcoding them within classes.

.NET Core’s built-in DI container differs from other frameworks like Autofac or Ninject in its simplicity and lightweight nature. While it provides basic features such as constructor, property, and method injection, it lacks advanced capabilities like interception or auto-registration. However, it can be easily replaced with third-party containers if needed.

In .NET Core, services are registered in the ConfigureServices method of the Startup class using IServiceCollection extension methods like AddTransient, AddScoped, and AddSingleton. These methods define the lifetime of the service instances.


public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient();
}
    

public class MyClass
{
    private readonly IMyService _myService;

    public MyClass(IMyService myService)
    {
        _myService = myService;
    }
}

17. What is the IGCToCLR interface?

IGCToCLR interface will be passed as an argument to the InitializeGarbageCollector() function and it is used for runtime communication. It consists of a lot of built-in methods such as RestartEE(), SuspendEE(), etc.

18. In what situations .NET Core and .NET Standard Class Library project types will be used?

.NET Core library is used if there is a requirement to increase the surface area of the .NET API which your library will access, and permit only applications of .NET Core to be compatible with your library if you are okay with it.

.NET Standard library will be used in case you need to increase the count of applications that are compatible with your library and reduce the surface area(a piece of code that a user can interact with) of the .NET API which your library can access if you are okay with it.

19. What is Transfer-encoding?

Transfer-encoding is used for transferring the payload body(information part of the data sent in the HTTP message body) to the user. It is a hop-by-hop header, that is applied not to a resource itself, but to a message between two nodes. Each multi-node connection segment can make use of various Transfer-encoding values.

Most modern web servers and clients support Transfer-Encoding and can handle chunked transfer encoding transparently. It's defined in the HTTP/1.1 specification (RFC 7230) and is widely used in practice.

20. What is the use of generating SQL scripts in the .NET core?

  1. Database Schema Management: Generating SQL scripts allows developers to manage database schema changes efficiently. By using tools like Entity Framework Core Migrations or other ORM (Object-Relational Mapping) frameworks, developers can generate SQL scripts to create, update, or rollback database schema changes based on changes made to the application's data model.
  2. Database Deployment: SQL scripts can be used to deploy database schema changes across different environments, such as development, testing, staging, and production.
  3. Database Versioning and Source Control: Generating SQL scripts allows developers to version control database schema changes along with application code.
  4. Database Backup and Recovery: By generating SQL scripts that include backup commands or data migration statements, developers can automate backup and recovery processes, ensuring data integrity and disaster recovery preparedness.
  5. Database Migration and Integration: By generating SQL scripts that contain data migration logic or integration routines, developers can automate data transfer tasks and ensure data consistency across different systems.
  6. Database Maintenance and Optimization: SQL scripts can be used to perform database maintenance tasks, such as indexing, data cleaning, or performance tuning.

Intermediate .NET Core Interview Questions

1. Explain the process of publishing a self-contained .NET Core application.

  1. Prepare the Application for Publishing: This includes building the application and verifying that it runs correctly on your development machine.
  2. Determine the Target Runtime: Determine the target runtime and operating system for which you want to publish the self-contained application.
  3. Choose the Publishing Command: In the .NET Core CLI (Command-Line Interface), you have several options for publishing a self-contained application:
    • dotnet publish: This command publishes the application for a specified target runtime and configuration.
    • dotnet publish -r: Use this command to specify the target runtime identifier explicitly.
    • dotnet publish -c Release: Specify the configuration (e.g., Release) for publishing the application.
  4. Publish the Application: Run the appropriate dotnet publish command from the terminal or command prompt.

    Example

    
    dotnet publish -c Release -r win-x64
    
  5. Verify the Published Output: After completing the publishing process, verify that the application has been published successfully. Navigate to the publish directory specified in the output of the dotnet publish command.
  6. Run the Published Application: Test the published application on the target system to ensure that it runs correctly. You can execute the application directly from the publish directory or distribute it to other systems.
  7. Deploy and Distribute the Application: Once you have verified that the self-contained application runs correctly, you can deploy and distribute it to users or deploy it to production environments as necessary.

2. How can you utilize the .NET Core CLI for developing, building, and deploying applications?

The .NET Core CLI is a powerful tool for developing, building, and deploying applications. To utilize it effectively:

  1. Install the .NET Core SDK to access the CLI commands.
  2. Use “dotnet new” to create a project template (e.g., console app, web app).
  3. Navigate to the project directory and use “dotnet restore” to install dependencies.
  4. Develop your application using your preferred IDE or text editor.
  5. Build the application with “dotnet build”, which compiles source code into executable files.
  6. Run the application locally using “dotnet run”.
  7. Deploy the application by publishing it with “dotnet publish”, generating a self-contained deployment or framework-dependent deployment.

3. Explain CoreRT.

In .NET Core, CoreRT has been used as a native toolchain that performs compilation to translation. In other words, it compiles CIL byte code to machine code. The CoreRT uses ahead-of-complier, RyuJIT for compilation. You can also use it with other compilers to perform native compilation for UWP apps.

The type system of the CoreRT is designed in such a way that metadata for reflection is not at all required. This feature enables to have an AOT toolchain that can link away unused metadata and identify unused application code.

4. How do you secure your .NET Core applications? Discuss the different authentication and authorization mechanisms available.

To secure .NET Core applications, implement authentication and authorization mechanisms. Authentication verifies user identity, while authorization determines access rights.

  1. Cookie-based: Use ASP.NET Core Identity for storing user information and managing authentication via cookies.
  2. Token-based: Utilize JSON Web Tokens (JWT) to authenticate users without server-side sessions.
  3. OAuth 2.0/OpenID Connect: Integrate with external providers like Google or Facebook using these protocols.
  4. Windows Authentication: Employ this mechanism in intranet scenarios where Active Directory is available.
  5. Certificate Authentication: Authenticate clients based on X.509 certificates, suitable for mutual TLS scenarios.

For authorization:

  1. Role-based: Grant access based on predefined roles assigned to users.
  2. Claims-based: Evaluate claims within a user’s identity to determine permissions.
  3. Policy-based: Define custom policies with specific requirements, evaluated by the Authorization Middleware.

5. How do you implement exception handling and logging in .NET Core applications?

In .NET Core applications, exception handling and logging are implemented using middleware components. Middleware is a chain of components that handle requests and responses in the application pipeline.

For exception handling, use the built-in “UseExceptionHandler” middleware to catch exceptions and provide custom error pages or responses. Configure it in the “Startup.cs” file within the “Configure” method:


app.UseExceptionHandler(options =>
{
    options.Run(async context =>
    {
        // Custom error response logic here
    });
});

For logging, utilize the ILogger interface provided by Microsoft.Extensions.Logging namespace. Inject ILogger into classes via dependency injection:


public class MyClass
{
    private readonly ILogger _logger;

    public MyClass(ILogger logger)
    {
        _logger = logger;
    }
}

Log messages with different severity levels: Trace, Debug, Information, Warning, Error, Critical:


_logger.LogInformation("This is an information log message.");

6. What is the hosting environment?

The hosting environment contains application-specific details such as application functions, where it is stored, services for app management, etc. A HostingEnvironment is created in the application domain, before the ASP's creation. In other words, a hosting environment is responsible for application management and app-specific functions.

This feature of .NET Core makes it possible for the developer to work with multiple environments, without creating any friction.

7. Explain response caching in .NET Core.

Response caching is when the .NET Core MVC's HTTP responses are pre-specified in cache-related headers. These headers describe how intermediate or client machines should cache responses to requests. This hence reduces the volume of requests the client or proxy machine makes to the web server.


// ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
}

// Configure method in Startup.cs
public void Configure(IApplicationBuilder app)
{
    app.UseResponseCaching();
    app.UseMiddleware();
}

// Controller action with ResponseCache attribute
[ResponseCache(Duration = 60)]
public IActionResult Index()
{
    // Action logic here
}

In this example, response caching middleware is added to the request pipeline, and the Index action in the controller is decorated with the ResponseCache attribute, specifying a cache duration of 60 seconds.

8. What is meant by state management?

Regarding .NET Core frameworks, state management is a kind of state control object to control the states of the object during different processes. Since stateless protocol, HTTP has been used, which is unable to retain user values; thus, different methods have been used to store and preserve the user data between requests.

Approach NameStorage Mechanism
CookiesHTTP Cookies, Server-side app code
Session stateHTTP Cookies, Server-side app code
Temp DataHTTP Cookies, Session State
Query StringsHTTP Query Strings
Hidden FieldsHTTP Form Fields
HTTPContext.ItemsServer-side app code
CacheServer-side app code

9. What is Docker?

  • Docker is an open-source platform for the development of applications, and also for shipping and running them. It allows for separating the application from the infrastructure using containers so that software can be delivered quickly. With Docker, you will be able to manage the infrastructure in the same ways you used to manage your applications.
  • It supports shipping, testing, and deploying application code quickly, thus reducing the delay between code writing and running it in production.
  • The Docker platform provides the ability to package and application execution in a loosely isolated environment namely a container. The isolation and security permit you to run multiple containers at the same time on a given host. Containers are lightweight and they include every necessary thing required for running an application, so you need not depend on what is currently installed within the host.

10. What's the difference between RyuJIT and Roslyn?

Roslyn is a .NET Core compiler that compiles VB or C# code to the intermediate language (IL). Whereas, RyuJIT as the name suggests is a Just-In-Time compiler that works the other way around i.e. compiles the IL to native code.

11. What is MEF?

The MEF(Managed Extensibility Framework) is a library that is useful for developing extensible and lightweight applications. It permits application developers to use extensions without the need for configuration. It also allows extension developers for easier code encapsulation thus avoiding fragile hard dependencies. MEF will let you reuse the extensions within applications, as well as across the applications. It is an integral part of the .NET Framework 4. It improves the maintainability, flexibility, and testability of large applications.

12. What are the benefits of using SignalR in .NET Core applications, and how does it differ from traditional AJAX-based communication?

SignalR in .NET Core offers real-time communication, enabling server-side code to push content updates instantly to connected clients. This contrasts with traditional AJAX-based communication, which relies on client-initiated requests and periodic polling for updates.

Key benefits of SignalR include:

  • Real-time functionality: Instantly update clients without requiring user interaction or page refreshes.
  • Automatic connection management: Handles connection persistence, reconnection, and scaling seamlessly.
  • Broad compatibility: Supports various platforms (web, mobile, desktop) and fallback mechanisms for older browsers.
  • High-level abstraction: Simplifies complex tasks like managing connections, groups, and message handling.
  • Extensibility: Customizable components allow adapting to specific requirements.

SignalR’s main difference from AJAX is its push-based approach, using WebSockets when available and falling back to other techniques (e.g., Server-Sent Events, Long Polling) if necessary. AJAX, conversely, employs a pull-based model where the client must request data explicitly.

13. What is Hosting Environment Management?

In .NET Core, the hosting environment represents the context in which the application is running. It provides information about the environment, such as whether the application is running in development, staging, or production mode.

  1. Environment Name: .NET Core applications define an environment name that indicates the current deployment environment. Common environment names include Development, Staging, Production, and others.
  2. IHostingEnvironment Interface: In ASP.NET Core, the IHostingEnvironment interface provides access to information about the hosting environment. It exposes properties such as EnvironmentName, ContentRootPath, and WebRootPath, which allow the application to determine its current environment and file system paths.
  3. WebHostBuilder: The ConfigureAppConfiguration method of the WebHostBuilder allows you to set up configuration sources and specify environment variables or command-line arguments that influence the hosting environment.
  4. AppSettings Configuration: By using separate appsettings files (e.g., appsettings.Development.json, appsettings.Production.json), you can define environment-specific configuration settings that are loaded based on the current environment.
  5. Environment-specific Middleware: ASP.NET Core allows you to register middleware based on the hosting environment conditionally. This enables you to add or remove middleware components depending on the deployment environment.
  6. Development vs. Production Mode: In Development mode, the application may have features enabled that aid in debugging and development, such as detailed error messages, developer exception pages, and automatic browser refresh (in client-side development).
  7. Integration with Dependency Injection: The hosting environment is often used in conjunction with dependency injection to configure services and components based on the current environment.

14. What are the various ways to manage errors in .NET Core for web APIs?

There are mainly four ways to manage errors in .NET Core for web APIs.

  1. Developer Exception Page
  2. Exception Handler Page
  3. Exception Handle Lambda
  4. UseStatusCodePages

If you compare these four methods, the best way is "Developer Exception Page" as it provides detailed information (stacks, query string parameters, headers, cookies) about unhandled request exceptions. You can easily enable this page by running your applications in the development environment. This page runs early in the middleware pipeline, so you can easily catch the exception in middleware.

15. How to figure out when to use .NET Core and .NET Standard Class Library project types?

  1. .NET Core Class Library
    • Use .NET Core class library projects when you need to create reusable components or libraries specifically targeting the .NET Core runtime.
    • .NET Core class libraries are typically used to build components that will be used within .NET Core applications, ASP.NET Core web applications, or other .NET Core projects.
    • .NET Core class libraries can take advantage of the features, performance optimizations, and APIs provided by the .NET Core runtime.
  2. .NET Standard Class Library
    • Use .NET Standard class library projects when you want to create reusable components or libraries that can be shared across different .NET implementations and runtimes.
    • .NET Standard class libraries are designed to provide a common API surface across multiple .NET platforms, including .NET Core, .NET Framework, Xamarin, and others.
    • .NET Standard class libraries are suitable for building libraries that need to target multiple .NET platforms or runtimes, ensuring compatibility and portability across different environments.

Advanced .NET Core Interview Questions for Experienced

1. Describe the role of the IConfiguration interface in .NET Core and provide examples of how to read configuration values from different sources.

In .NET Core, the IConfiguration interface plays a central role in managing application configuration settings. It provides a unified way to access configuration values from various configuration sources, such as appsettings.json files, environment variables, command-line arguments, user secrets, Azure Key Vault, and custom configuration providers.

To read configuration values, first install the required NuGet packages for the desired configuration providers (e.g., Microsoft.Extensions.Configuration.Json). Then, create a ConfigurationBuilder instance, add the necessary providers, and build the configuration object.

  1. appsettings.json Files
    
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");
    IConfiguration configuration = builder.Build();
    string value = configuration["MySetting"];    
  2. Environment Variables
    
    var builder = new ConfigurationBuilder().AddEnvironmentVariables();
    IConfiguration configuration = builder.Build();
    string value = configuration["MY_ENVIRONMENT_VARIABLE"];
    
  3. Command-Line Arguments
    
    string[] args = { "--mysetting=value" };
    var builder = new ConfigurationBuilder().AddCommandLine(args);
    IConfiguration configuration = builder.Build();
    string value = configuration["mysetting"];    

2. Differentiate between Blazor Server and Blazor WebAssembly. How do you decide which one to use for a particular project?

Differentiate between Blazor Server and Blazor WebAssembly

Blazor WebAssemblyBlazor Server
Web app with client-side execution loaded from web server can work offline via a service worker.Every interaction handled on server prerendered HTML
The Main() method determines the basic components of the application the components are in the App.razor fileThe Main() method calls the CreateHostBuilder method which sets the ASP.Net Core hosts.
It's run in the browser using WebAssemblyIt's run on the server
Single Page ApplicationUse SignalIR to update the client.
Progressive Web App(PWA)Fast processing large amounts of data

Differentiate between Blazor Server and Blazor WebAssembly

To decide which model to use, consider these factors:

  1. Latency: If low latency is crucial, choose Blazor WebAssembly.
  2. Offline capability: For offline functionality, opt for Blazor WebAssembly.
  3. Client resources: If targeting less powerful devices or slow networks, Blazor Server may be preferable.
  4. Server load: Blazor Server increases server load; if minimizing this is important, select Blazor WebAssembly.
  5. Compatibility: Blazor WebAssembly requires modern browsers; for broader compatibility, use Blazor Server.
  6. Code sharing: Both models allow code sharing between client and server, but Blazor WebAssembly enables greater flexibility.

3. What is Generic Host in .NET Core?

In .NET Core, the Generic Host is a new hosting model for building lightweight and cross-platform console applications, background services, and microservices. It provides a simplified and consistent way to configure, start, and run .NET Core applications outside of the ASP.NET Core framework.

The Generic Host is built on top of the HostBuilder API, which is part of Microsoft.Extensions.Hosting namespace. It allows developers to configure application services, logging, configuration, and other components using a fluent and builder-style syntax.

Let's see how to create and configure a Generic Host in a .NET Core console application:


using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await new HostBuilder()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService();
            })
            .ConfigureLogging(logging =>
            {
                logging.AddConsole();
            })
            .RunConsoleAsync();
    }
}

public class MyBackgroundService : BackgroundService
{
    private readonly ILogger _logger;

    public MyBackgroundService(ILogger logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Background service is running...");
            await Task.Delay(1000, stoppingToken);
        }
    }
}

4. What about MVC in .NET Core?

MVC (Model-View-Controller) is a popular architectural pattern for building web applications, and it's also a key component of ASP.NET Core. MVC in ASP.NET Core follows the same principles as traditional MVC frameworks but with some enhancements and features tailored for modern web development.

MVC in .NET Core

ASP.NET Core MVC Features

  • Routing: ASP.NET Core MVC includes a flexible routing system that maps incoming HTTP requests to controller actions based on URL patterns.
  • Model Binding: Model binding automatically maps incoming request data (e.g., form values, query string parameters) to action method parameters or model properties.
  • Views and Razor Syntax: Views in ASP.NET Core MVC use the Razor view engine, which allows developers to write HTML with embedded C# code to generate dynamic content.
  • Tag Helpers: Tag Helpers are a feature in ASP.NET Core MVC that enables developers to create and use HTML-friendly syntax to generate and work with HTML elements and attributes within Razor views.
  • Filters: Filters are used to add pre-action or post-action behavior to controller actions. Examples include authorization filters, exception filters, action filters, and result filters.
  • Middleware Pipeline Integration: ASP.NET Core MVC integrates seamlessly with the ASP.NET Core middleware pipeline, allowing you to combine MVC with other middleware components for features such as authentication, authorization, logging, and error handling.
  • Dependency Injection: ASP.NET Core MVC fully embraces dependency injection, making it easy to inject services and dependencies into controllers, views, filters, and other components.
  • Testing Support: ASP.NET Core MVC provides support for unit testing controllers and actions using testing frameworks like xUnit or NUnit.

The Startup class is the entry point for configuring services and middleware in an ASP.NET Core application. In the ConfigureServices method, you can register services with the dependency injection container, including MVC services.

5. Explain the types of deployment for .NET Core applications.

.NET Core applications can be deployed in various ways, depending on factors such as application complexity, infrastructure requirements, and deployment preferences. Two common types of deployment for .NET Core applications are:

  1. Self-Contained Deployment (SCD)
    • In this, the .NET Core runtime and all application dependencies are included with the application package.
    • The application is bundled with the specific version of the .NET Core runtime required to run it, ensuring that the application can run on systems where the runtime is not installed.
    • Self-contained deployments are typically larger compared to framework-dependent deployments because they include runtime and dependencies.
    • Self-contained deployments are useful when targeting platforms where the .NET Core runtime may not be available or when you want to isolate the application's runtime environment from other applications on the system.
    • You can create self-contained deployments using the dotnet publish command with the appropriate runtime identifier (RID) specified.
  2. Framework-Dependent Deployment (FDD)
    • Here, the .NET Core runtime is installed separately on the target system, and the application relies on the installed runtime to execute.
    • The application package contains only the application binaries and dependencies, without including the .NET Core runtime.
    • Framework-dependent deployments are smaller in size compared to self-contained deployments because they do not include the runtime.
    • Framework-dependent deployments are suitable for environments where the .NET Core runtime is already installed, such as development machines, build servers, or containerized environments.
    • You can create framework-dependent deployments using the dotnet publish command without specifying a runtime identifier (RID), which defaults to the host system's platform.

6. What officially replaces WCF in .NET Core?

In .NET Core, there isn't a direct replacement for Windows Communication Foundation (WCF) as a single, unified communication framework. Instead, .NET Core offers several alternatives and technologies.

  • ASP.NET Core Web API: It is a lightweight and modern framework for building HTTP-based APIs using RESTful principles. ASP.NET Core Web API supports various features such as model binding, routing, middleware, content negotiation, and JSON serialization.
  • gRPC: A high-performance RPC (Remote Procedure Call) framework developed by Google. It uses protocol buffers (protobuf) as the interface definition language and provides features such as bi-directional streaming, authentication, and cancellation.
  • ASP.NET Core gRPC: It includes built-in support for creating gRPC services using ASP.NET Core middleware. ASP.NET Core gRPC allows you to define and implement gRPC services using C# and integrates seamlessly with ASP.NET Core features such as middleware, dependency injection, and routing.
  • ASP.NET Core SignalR: It enables bi-directional communication between clients and servers over a single, persistent connection. It is suitable for scenarios requiring real-time updates, such as chat applications, live dashboards, and multiplayer games.
  • Azure Communication Services: It is a suite of cloud-based communication APIs provided by Microsoft Azure. It offers APIs for building voice calling, video calling, SMS messaging, and chat functionality into applications.

7. Explain the implicit compilation process in .NET Core.

In .NET Core, the implicit compilation process refers to the automatic compilation of C# source code files into executable code without the need for explicit compilation commands. This process is facilitated by the .NET Core SDK and the underlying build system.

Here's an overview of the working of the implicit compilation process in .NET Core:

  1. Project Structure: In a typical .NET Core project, C# source code files (*.cs) are organized within a project directory structure. The project also contains a project file (usually with a .csproj extension) that defines project metadata, dependencies, and build configurations.
  2. dotnet CLI: The .NET Core command-line interface (CLI) provides commands for managing .NET Core projects, including building, running, testing, and publishing applications. The dotnet CLI is used to perform various development and build tasks from the command line.
  3. Project File: The project file (e.g., MyProject.csproj) contains XML-based configurations that specify project settings, dependencies, target frameworks, and build instructions. It defines the structure and behavior of the project and provides instructions to the build system on how to compile the project.
  4. Dependency Resolution: Before compilation, the .NET Core SDK resolves project dependencies and ensures that all required packages and libraries are available. It downloads missing packages from package repositories such as NuGet.org and restores dependencies as necessary.
  5. Build Process: When you build a .NET Core project using the dotnet CLI (e.g., dotnet build command), the SDK invokes the build system to compile the project's source code files into executable code. The build system uses MSBuild, the Microsoft Build Engine, to orchestrate the compilation process.
  6. Compilation Tasks: During the compilation process, the build system performs various tasks, including parsing C# source code files, resolving references, compiling source code into Intermediate Language (IL) bytecode, and generating executable binaries (e.g., DLLs, EXEs).
  7. Incremental Builds: The .NET Core build system supports incremental builds, which means that only modified source code files and their dependencies are recompiled during subsequent builds. This improves build performance by avoiding unnecessary recompilation of unchanged files.
  8. Output Artifacts: After successful compilation, the build system produces output artifacts such as DLLs, EXEs, and other files specified in the project configuration. These artifacts represent the compiled application or library and can be executed, tested, or published for distribution.

8. What is Scaffolding in ASP.NET MVC?

Scaffolding in ASP.NET MVC is a code generation technique used to quickly create basic CRUD (Create, Read, Update, Delete) functionality for database entities. It automates the process of generating controller, views, and data access code based on the model classes representing the database entities.

Additionally, the framework includes multiple templates, including page templates, field templates, entity page templates, and filter templates. You can call them Scaffold templates. These templates permit you to design and build a fully functional website.

9. How does ASP.NET Core handle static file serving?

  • ASP.NET Core doesn't serve static files like images, HTML, or CSS by default. Instead, it relies on the UseStaticFiles middleware to handle this task.
  • You configure this middleware to point to your static file folder, typically wwwroot.
  • Then, the middleware intercepts requests for these files and delivers them directly to the client, bypassing the entire ASP.NET Core pipeline.
  • This keeps things fast and efficient. Additionally, you can control caching and authorization for static files to further optimize your application.

10. What are Universal Windows Platform(UWP) Apps in .Net Core?

Universal Windows Platform(UWP) is one of the methods used to create client applications for Windows. UWP apps will make use of WinRT APIs for providing powerful UI as well as features of advanced asynchronous that are ideal for devices with internet connections.

Features of UWP apps:

  • Cross-Device Compatibility: UWP apps are designed to run on a variety of Windows 10 devices, including PCs, tablets, smartphones, Xbox consoles, Surface Hub, and HoloLens devices.
  • Responsive Design: UWP apps support responsive design principles, allowing developers to create adaptive user interfaces that scale and adjust layout dynamically based on screen size, orientation, and resolution.
  • Modern UI Controls: UWP provides a rich set of modern UI controls and components that enable developers to create visually appealing and interactive user interfaces.
  • Live Tiles and Notifications: UWP apps can utilize Live Tiles on the Start menu to display dynamic content, updates, and notifications to users.
  • Background Tasks and Services: UWP apps support background tasks and services that allow applications to perform tasks and process data even when they're not in the foreground.
  • App Services and APIs: UWP apps can leverage platform APIs and app services to access system features, device hardware, and platform capabilities. This includes accessing sensors, cameras, location services, contacts, calendars, and other device-specific functionality through secure and sandboxed APIs.
  • Security and App Containerization: UWP apps run in a secure and isolated app container environment that protects against malicious code, unauthorized access to system resources, and data breaches.
  • App Distribution and Store Integration: UWP apps can be distributed and installed through the Microsoft Store, providing a centralized marketplace for users to discover, download, and install applications.
  • Single Codebase and Deployment: UWP apps can be built using a single codebase and deployed to multiple device types without requiring separate versions or modifications.
  • Integration with Windows Features: UWP apps seamlessly integrate with various Windows features and services, including Cortana, Windows Ink, etc.

11. What is MSBuild in the .NET Core?

MSBuild is a free and open-source development platform for Visual Studio and Microsoft. It is a build tool that helps automate the software product creation process, along with source code compilation, packaging, testing, deployment, and documentation creation. Using MSBuild, we can build Visual Studio projects and solutions without the need to install the Visual Studio IDE.

12. What is Xamarin?

  • Xamarin is an open-source platform useful in developing a modern and efficient application for iOS, Android, and Windows with .NET. It is an abstraction layer used to manage the communication of shared code with fundamental platform code.
  • Xamarin runs in a managed environment that gives benefits like garbage collection and memory allocation.
  • Developers can share about 90% of their applications over platforms using Xamarin. This pattern permits developers to write entire business logic in a single language (or reuse existing app code) but accomplishes native performance, look, and feel on each platform. The Xamarin applications can be written on Mac or PC and then they will be compiled into native application packages, like a .ipa file on iOS, or .apk file on Android.

13. Why is Startup Class important?

The Startup is a critical class in the application. The following points make it imperative:

  • It describes the pipeline of the web applications.
  • You can use individual startups for each environment.
  • It helps to perform the registration of all required middleware components.
  • Reading and checking thousands of lines in different environments is tough, but you can use various startup classes to resolve it.

14. What is CTS in .NET Core?

CTS in .NET Core

In .NET Core, CTS stands for Common Type System. The Common Type System is a fundamental component of the .NET runtime environment that defines how types are declared, used, and managed across different programming languages supported by the .NET platform.

CTS is a single-rooted object hierarchy where the System object is the base type for the derivation of all other types. Two major kinds of types it supports are:

  1. Value Types: These types are either allocated within the structure inline or are stored directly in the stack. This includes built-in value types (standard primitive types), types defined in source code, user-defined value types, enumerations, etc.
  2. Reference Types: These store value memory address references and are allocated on the heap. They may be any of the interface types, pointer types, or self-describing types. For example- class types and arrays like boxed value types, delegates, user-defined classes, etc.

15. How is .NET Core SDK different from .NET Core Runtime?

.NET Core SDK builds applications, whereas .NET Core Runtime runs the application. Consider SDK is a collection of all tools and libraries you need to develop .NET Core applications quickly like a compiler, and CLI. Consider Runtime as a virtual machine consisting of runtimes libraries that help you run those applications.

Read more:

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this