DEV Community

Cover image for [Part 4] If You Can Answer These Additional 7 Questions Correctly, You’re Decent at .NET
Sukhpinder Singh
Sukhpinder Singh

Posted on • Originally published at Medium

[Part 4] If You Can Answer These Additional 7 Questions Correctly, You’re Decent at .NET

Hello .NET Enthusiasts,

Welcome to Part 4 of our C# knowledge test challenge! Please go through the series here.
C# .Net Interview Series

The next set of questions will test your knowledge of advanced .NET concepts and practices.

1. Exploring .NET Core Data Protection

Data protection is one of the key features in modern applications that keep data secure. In this regard, .NET Core provides its Data Protection API to handle different aspects like encryption and decryption.

How does the Data Protection API work in .NET Core, and how would you use it to protect data

Answer: The Data Protection API helps to securely encrypt and decrypt data. It uses keys and can store those in various locations such as files or Azure Key Vault.

Configure Data Protection in Startup.cs:

public void ConfigureServices(IServiceCollection services) 
{     
    services.AddDataProtection();
}
Enter fullscreen mode Exit fullscreen mode

Encrypt and Decrypt Data:

public class DataProtectionExample 
{
    private readonly IDataProtector _protector; 
    public DataProtectionExample(IDataProtectionProvider provider) 
    {         
        _protector = provider.CreateProtector("MyApp.Purpose");     
    } 
    public string Encrypt(string plainText) 
    {         
        return _protector.Protect(plainText);     
    } 
    public string Decrypt(string cipherText) 
    {         
        return _protector.Unprotect(cipherText);     
    } 
}
Enter fullscreen mode Exit fullscreen mode

Using Data Protection API ensures that the sensitive data is encrypted and decrypted in a safe way.

2. Implementing and Using .NET Core Custom Exception Filters

ASP.NET Core Exception filters can be applied globally or to specific controllers. This will help in implementing centralized error handling. Also, custom exception filters will be very helpful.

How to implement a custom exception filter in ASP.NET Core? Create a simple example.

Answer: To create a custom exception filter:

Create the Exception Filter:

public class CustomExceptionFilter : IExceptionFilter 
{
    public void OnException(ExceptionContext context) 
    {
        // Log the exception (example)
        Console.WriteLine(context.Exception.Message); 
        context.Result = new ContentResult
        {
            Content = "An error occurred!",
            StatusCode = StatusCodes.Status500InternalServerError
        };
    }
}
Enter fullscreen mode Exit fullscreen mode

Register the Filter in Startup.cs:

public void ConfigureServices(IServiceCollection services) 
{
    services.AddControllers(options =>
    {
        options.Filters.Add<CustomExceptionFilter>();
    });
}
Enter fullscreen mode Exit fullscreen mode

The Custom Exception Filters provide a way for you to handle exceptions in an consistent way throughout your application.

3. Advanced LINQ: Deferred vs. Immediate Execution

One can execute LINQ queries in one of two ways: immediate execution or deferred. Understanding the difference can be important in optimizing performance and controlling when queries are executed.

Highlight a code example to demonstrate difference deferred and immediate execution in LINQ?

Answer:

  • Deferred Execution: Execution of a query is delayed until the query is enumerated.

Deferred Execution:

The query is not executed until you iterate over it.

var query = numbers.Where(n => n % 2 == 0); 
// Query is not executed until you iterate over it

foreach (var number in query) 
{     
    Console.WriteLine(number); 
}
Enter fullscreen mode Exit fullscreen mode

Immediate Execution:

The query is executed as soon as it is defined.

var result = numbers.Where(n => n % 2 == 0).ToList(); 
// Query is executed immediately, and result is a List<int>
Enter fullscreen mode Exit fullscreen mode

Defer execution is useful when you want to build up queries dynamically, and immediate execution is useful when you need immediately results of the query.

4. Understanding and Implementing Caching in .NET Core

Caching is one of the most effective ways of enhancing application performance by keeping repetitive data in persistent storage. .NET Core has different caching mechanisms which handle this.

How will you implement caching in ASP.NET Core using in-memory caching? Give an example.

Answer: To implement in-memory caching:

Configure In-Memory Caching in Startup.cs:

public void ConfigureServices(IServiceCollection services) 
{     
    services.AddMemoryCache();
}
Enter fullscreen mode Exit fullscreen mode

Use In-Memory Cache in a Service:

public class MyService 
{
    private readonly IMemoryCache _cache; 
    public MyService(IMemoryCache cache) 
    {         
        _cache = cache;     
    } 
    public string GetCachedData(string key) 
    {         
        if (!_cache.TryGetValue(key, out string data))         
        {             
            // Simulate data retrieval             
            data = "Some data";             
            var cacheEntryOptions = new MemoryCacheEntryOptions
            {                 
                SlidingExpiration = TimeSpan.FromMinutes(1)             
            };             
            _cache.Set(key, data, cacheEntryOptions);         
        }         
        return data;     
    } 
}
Enter fullscreen mode Exit fullscreen mode

Caching in memory improves performance by avoiding the need to fetch data repeatedly from slow sources.

5. Exploring .NET Core’s Built-in Logging Providers

Logging is vital for both problem diagnosis and application monitoring. .NET Core has several providers that are out of the box and can be utilized.

How do I configure and utilize the built-in logging providers within .NET Core? Include an example of establishing logging to the console.

Configure Logging in Startup.cs:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 
{     
    loggerFactory.AddConsole(); // Adds console logging
    app.Use(async (context, next) => 
    {         
        var logger = loggerFactory.CreateLogger("RequestLogger");         
        logger.LogInformation("Handling request: " + context.Request.Path);         
        await next();         
        logger.LogInformation("Finished handling request.");     
    });
}
Enter fullscreen mode Exit fullscreen mode

Inject ILogger in Services:

public class MyService 
{
    private readonly ILogger<MyService> _logger; 
    public MyService(ILogger<MyService> logger) 
    {         
        _logger = logger;     
    } 
    public void DoWork() 
    {         
        _logger.LogInformation("Doing work...");     
    } 
}
Enter fullscreen mode Exit fullscreen mode

Logging providers help in capturing and managing application logs efficiently.

6. Understanding and Using ValueTask in .NET

ValueTask is a structure which helps in better performance by reducing allocations when one is dealing with asynchronous operations.

What is the ValueTask, and when to use ValueTask instead of Task? Provide example.

ValueTask Is a struct that can be used as an alternative to Task when the result is already available, or the task completes synchronously.

Example:

public async ValueTask<int> GetNumberAsync(bool quick)
{
    if (quick)
    {
        return 42; // Return synchronously
    }
    else
    {
        await Task.Delay(1000); // Simulate async operation
        return 42;
    }
}
Enter fullscreen mode Exit fullscreen mode

Use ValueTask when you want to avoid allocations for methods that frequently complete synchronously or when performance is critical.

7. Exploring ASP.NET Core Health Checks

Application is running correctly or not can be checked via Health checks and can be used to monitor application health in production environments.

Share an example of how you configure health checks in ASP.NET Core.

Add Health Check Services in Startup.cs:

public void ConfigureServices(IServiceCollection services) {     
   services.AddHealthChecks(); 
}
Enter fullscreen mode Exit fullscreen mode

Configure Health Check Endpoints:

public void Configure(IApplicationBuilder app) {     
   app.UseHealthChecks("/health"); 
}
Enter fullscreen mode Exit fullscreen mode

Example Health Check:

public class CustomHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(CancellationToken cancellationToken = default)
    {
        // Perform health check logic
        bool isHealthy = true;
        return Task.FromResult(isHealthy ? HealthCheckResult.Healthy("The service is healthy") : HealthCheckResult.Unhealthy("The service is unhealthy"));
    }
}
Enter fullscreen mode Exit fullscreen mode

Health checks offer essential functionality when monitoring whether your application is healthy and ready for production environments.

So, how did you do?

If you know the concept with confidence and understand the code examples, you’re likely well-versed in .NET.

Let’s keep the conversation going and help each other grow as .NET professionals.

Happy coding!

Top comments (0)