Hello .NET Enthusiasts,
Welcome to Part 6 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. Abstract Classes v/s Interfaces
What’s the difference between abstract classes and interfaces? Examples of both.
Abstract Classes
Can include fields, constructors and destructors.
Useful when you have a base class with some shared code and want to provide common functionality to derived classes.
Example
public abstract class Shape {
public abstract void Draw();
public void Move() { /* Implementation */ }
}
public class Circle : Shape {
public override void Draw() { /* Implementation */ }
}
Interfaces
Can only contain method signatures, properties, events, and indexers (no implementation).
One class can implement many interfaces.
Really for declaring a contract that can be implemented by several classes.
Example
public interface IDrawable {
void Draw();
}
public class Circle : IDrawable {
public void Draw() { /* Implementation */ }
}
Use abstract classes when you need shared code and a base class. Use interfaces to define a contract that many classes can implement.
2. Async Modifier
Explain what the async modifier in C# does. What are its effects on how a method runs, and what are its key advantages?
The async keyword in C# is used when declaring an asynchronous method. You may apply the await keyword inside the method that is declared with this keyword. Using this modifier, therefore, you can write asynchronous code and still have a non-blocking main thread for the long-running operations.
Example
public async Task<string> FetchDataAsync() {
await Task.Delay(2000); // Simulates a delay
return "Data fetched";
}
The async modifier simplifies asynchronous programming and helps maintain application performance.
3. Cross-Origin Resource Sharing (CORS)
How does .NET Core handle Cross-Origin Resource Sharing (CORS)?
By using .NET Core, it is very possible to configure CORS so that it allows some origins, methods, and headers but disallows others.
Mastering CORS: 10 Crucial Tips for Effective Implementation
Example: Configure CORS in Startup.cs:
public void ConfigureServices(IServiceCollection services) {
services.AddCors(options => {
options.AddPolicy("AllowSpecificOrigin", builder => {
builder.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app) {
app.UseCors("AllowSpecificOrigin");
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
4. IServiceProvider
Explain the role of IServiceProvider in .NET Core. How is it used in dependency injection?
IServiceProvider is the interface in .NET Core. It offers the ability to implement a way of service resolution with lifetime management for services. It’s an essential component of Dependency Injection.
Example:
public class MyService {
public void DoWork() { /* Implementation */ }
}
// Resolving a service
public class HomeController : Controller {
private readonly MyService _myService;
public HomeController(IServiceProvider serviceProvider) {
_myService = serviceProvider.GetService<MyService>();
}
}
IServiceProvider is very critical to resolve and manage the dependencies in an application.
5. Configuration Providers
What are configuration providers in .NET Core? How is it used in dependency injection?
Configuration providers are .NET Core components that feed configuration data from multiple sources into your application, such as JSON files, environment variables, and command-line arguments. The configuration system populates configuration values based on these providers.
Example: Configuration Sources in Startup.cs:
public void ConfigureAppConfiguration(IConfigurationBuilder builder) {
builder.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args);
}
Using Configuration Values:
public class MyService {
private readonly IConfiguration _configuration;
public MyService(IConfiguration configuration) {
_configuration = configuration;
}
public string GetSetting() {
return _configuration["MySetting"];
}
}
Configuration providers enable flexible and dynamic configuration management in .NET Core applications.
6. Logging
How to add logging in an ASP.NET Core application.
ASP.NET Core has a built-in logging framework that supports several types of providers from the environment of different platforms, including Console, Debug, and File.
Example: Configure Logging in Startup.cs:
public void ConfigureServices(IServiceCollection services) {
services.AddLogging(builder => {
builder.AddConsole()
.AddDebug();
});
}
Use Logging in Code:
public class MyController : Controller {
private readonly ILogger<MyController> _logger;
public MyController(ILogger<MyController> logger) {
_logger = logger;
}
public IActionResult Index() {
_logger.LogInformation("Index action method called.");
return View();
}
}
7. Middleware
What is middleware? What does it serve in ASP.NET Core?
It manages HTTP requests and responses using a pipeline through which each middleware can process a request.
Creating Custom Middleware: Define Middleware:
public class CustomMiddleware {
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
// Custom logic before the request is processed
await context.Response.WriteAsync("Hello from Custom Middleware!");
await _next(context); // Call the next middleware
}
}
Register Middleware in Startup.cs:
public void Configure(IApplicationBuilder app) {
app.UseMiddleware<CustomMiddleware>();
}
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)