April 28, 2023

Minimal Api

Minimal API in .NET Core is a new approach to building web APIs with minimal ceremony and less boilerplate code. It is a feature that was introduced in .NET 6 and has been improved in subsequent versions, including .NET 7.

With Minimal API, developers can create HTTP endpoints with fewer lines of code and without having to set up complex routing or middleware configurations. This is achieved by providing a simplified syntax for defining endpoints, which reduces the amount of code required to create an API.

A simple example:


    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;

    var builder = WebApplication.CreateBuilder(args);

    var app = builder.Build();

    app.MapGet("/", () => "Hello World!");

    app.Run();

The goal of Minimal API is to enable developers to focus on writing business logic rather than dealing with infrastructure concerns. It provides a streamlined development experience, making it easier and faster to build APIs. Additionally, Minimal API integrates seamlessly with other .NET Core technologies, such as Dependency Injection and Entity Framework Core.

Another example for coherent code structure:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapPost("/change-password", UserEndpoints.ChangePassword);

app.Run();

public static class UserEndpoints
{
public static async Task<IResult> ChangePassword(
                                    HttpContext context,
                                    ChangePasswordRequest request,
                            IUserService userService)
{
//Logic here
return await Task.FromResult(Results.Ok());
}
}

Overall, Minimal API in .NET Core provides a lightweight, modern approach to building web APIs, enabling developers to quickly create high-performance, scalable APIs with minimal effort. 

I will be writing quite a bit of minimal api usages and best practices in future. So stay tuned.  

April 26, 2023

Pattern matching using C# Switch expressions

Switch expressions pattern matching provides developers with a concise and expressive way to handle complex conditional logic. It allows you to match patterns within a switch expression, rather than just values.

One of the key benefits of switch expressions pattern matching is that it reduces the amount of code you need to write to handle different cases. This can make your code more readable, maintainable, and efficient.

Here's an example of how you can use switch expressions pattern matching in C#:

public string Execute(ICommand command) => (command) switch
{
OpenCommand o => "Open Command",
CloseCommand o => "Close Command",
ExecuteCommand o => "Execute Command",
_ => throw new ArgumentOutOfRangeException(nameof(command), command, null)
};

In the above example, we define a method called Execute that takes an ICommand object as a parameter. We then use a switch expression to match the type of the command and return the corresponding action. Also it is far easier to use pattern matching on the properties of the paratmers. 

public string Execute(ICommand command) => (command) switch
{
{ Valid: true } and {Value: > 10 }=> "Open Command",
{ Valid: false } and {Value: <= 10 } => "Close Command",
ExecuteCommand o => "Execute Command",
_ => throw new ArgumentOutOfRangeException(nameof(command), command, null)
};

The switch expression uses the arrow notation (=>) to match the pattern and return the result. The _ symbol acts as a catch-all case, which throws an exception if an invalid command is passed in.

Tuples significantly improves the pattern matching as shown in the below example.

private static string FormatMobileNumber(string number) =>
(number.StartsWith("+6"), number.StartsWith("6"), number.StartsWith("04")) switch
{
(true, _, _) => number,
(false, true, _) => $"+61{number[1..]}",
(false, false, true) => $"+61{number[1..]}",
_ => number
};

Overall, switch expressions pattern matching is a powerful feature in C# that can help you write more expressive and maintainable code. Whether you're working on a small project or a large enterprise application, it's definitely worth considering using switch expressions pattern matching in your code.