.NET 9 Features with Code Example

.NET 9 core features are discussed here to know some of the important added new developer favorite features.

String Literals

Raw String Literals is one of C# 11 features it allows without adding escape sequences and can include multi-line strings.

var jsonString = """
{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}
""";

Required Member

The "required" keyword was added for mentioning class members as a required field. Object initialization requires class members to declare.

public class Person
{
    public required string Name { get; init; }
    public required int Age { get; init; }
}

// class usage
var person = new Person { Name = "Alice", Age = 25 };// Valid
var person = new Person { Age = 25 }; // In Valid Compile error

File Scoped Types

improve encapsulation by defining types that are scoped to a single file.

file class HelperClass
{
    public static string GetMessage() => "This is a helper.";
}

//Usage in the same file
Console.WriteLine(HelperClass.GetMessage());

Compatibility and Migration

Migrating application .Net 6/7/8 to .Net 9 update is allowed directly to better development features.

Hot Reload

.Net 9 allows application changes by adding code directly reflecting in output like Hot reload.

// Before change
Console.WriteLine("Hi");

// After change
Console.WriteLine("Hi .Net 9 feature");

Cross-platform Development

.Net MAUI app development simple enhanced UI.

public class MainPage : ContentPage
{
    public MainPage()
    {
        var label = new Label
        {
            Text = "Welcome to Cross platform .NET MAUI!",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        };
        Content = new StackLayout
        {
            Children = { label }
        };
    }
}

Enhanced Minimal API

For lightweight web application development Minimal API feature is making simple endpoint.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Launch Web application..");
app.Run();

Improved Error Handling

Setting Security header features to prevent sensitive information in error messages from attackers. Example of how to set security headers in an ASP.NET Core application.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    Add security headers
    app.Use(async (context, next) =>
    {
        context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
        context.Response.Headers.Add("X-Frame-Options\", "DENY");
        context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'");
        await next();
    });
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}