Code Examples for .NET 8 Features with C# 12

Overview

With .NET 8, a suite of new features and improvements are included to enhance performance, introduce advanced language features, and broaden cross-platform support for the .NET framework. With practical code examples, this article explores the key updates in .NET 8, focusing on performance improvements and new language capabilities in C# 12.

Key Features in .NET 8


Performance Enhancements


Improved JIT Compiler

As a result of .NET 8's Just-In-Time (JIT) compiler improvements, your code might run faster and have less overhead.

// Example of optimised JIT compilation
namespace DotNet8FeaturesApp;

public static class MathOperations
{
    public static int Sum(int[] numbers)
    {
        int total = 0;
        foreach (int number in numbers)
        {
            total += number;
        }
        return total;
    }
    
    public static void DisplaySum(int[] numbers)
    {
        int sum = Sum(numbers);
        Console.WriteLine(sum switch
        {
            0 => "The array is empty.",
            > 0 => $"The sum is {sum}.",
            _ => "An error occurred."
        });
    }

}
using DotNet8FeaturesApp;

Console.WriteLine("Hello and welcome to Article Code Examples for .NET 8 Features with C# 12 by Ziggy Rafiq");

int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(MathOperations.Sum(numbers));
MathOperations.DisplaySum(numbers);

Enhanced Garbage Collection

In .NET 8, garbage collection (GC) is optimized to reduce pauses, which is especially helpful for high-throughput applications.

 namespace DotNet8FeaturesApp;
public class LargeObject
{
    private byte[] _data = new byte[10_000_000];
    public void UseLargeObject()
    {
        Console.WriteLine($"LargeObject with {_data.Length} bytes created.");
    }
}

public record LargeObjectStatus(bool IsInUse, int Size);
var largeObject = new LargeObject();
largeObject.UseLargeObject();

var status = new LargeObjectStatus(IsInUse: true, Size: 10_000_000);
Console.WriteLine(status switch
{
    { IsInUse: true, Size: > 0 } => $"Large object is in use with size {status.Size} bytes.",
    _ => "Large object status is unknown."
});

Faster Startup Times

Runtime and library optimizations make applications start up faster:

Console.WriteLine("This Application has started quickly!");

Language Enhancements in C# 12


Enhanced Pattern Matching

Using C# 12, you can perform more powerful pattern matching. For example, you can:

 namespace DotNet8FeaturesApp;

public static class TypeDescriptor
{
    public static string Describe(object obj) =>
        obj switch
        {
            int i when i > 0 => "Positive integer",
            int i when i < 0 => "Negative integer",
            string s => $"String of length {s.Length}",
            double d when d > 0 => "Positive double",
            DateTime dt => $"DateTime value: {dt:yyyy-MM-dd}",
            _ => "Unknown type"
        };
}
Console.WriteLine(TypeDescriptor.Describe(42));
Console.WriteLine(TypeDescriptor.Describe("Hello Reader"));
Console.WriteLine(TypeDescriptor.Describe(3.14)); 
Console.WriteLine(TypeDescriptor.Describe(DateTime.Now));
Console.WriteLine(TypeDescriptor.Describe(null));

Record Types Enhancements

Interoperability has been improved, and non-destructive mutations are now supported:

 namespace DotNet8FeaturesApp;

public record Person(string FirstName, string LastName)
{
     public Person WithNewLastName(string newLastName) =>
        this with { LastName = newLastName };
}
var person = new Person("Mike", "Joe");
var updatedPerson = person.WithNewLastName("Walker");
Console.WriteLine(updatedPerson);

Nullable Reference Types Refinements

For better nullability handling, nullable reference types have been improved:

 namespace DotNet8FeaturesApp;

public static class NullabilityExample
{
    public static void PrintLength(string? text)
    {
        Console.WriteLine(text is not null ? text.Length.ToString() : "Text is null ok");
    }
}
NullabilityExample.PrintLength("Hi");
NullabilityExample.PrintLength(null);

New Libraries and APIs


Enhanced System.Text.Json

Improved handling of complex JSON is possible with System.Text.Json:

namespace DotNet8FeaturesApp;
using System.Text.Json;
public class Human
{
    public string Name { get; set; }=string.Empty;
    public int Age { get; set; }
}
var json = "{\"Name\":\"Lisa\",\"Age\":28}";
var human = JsonSerializer.Deserialize<Human>(json);

Console.WriteLine($"Name: {human?.Name}, Age: {human?. Age}");

New System.Device Namespace

It simplifies hardware interaction with the new namespace System.Device:

using System.Device.Gpio;
using var gpioController = new GpioController();
gpioController.OpenPin(18, PinMode.Output);
gpioController.Write(18, PinValue.High);
Console.WriteLine("Pin 18 set to High");

Advanced Networking APIs

Support for modern scenarios is enhanced by networking APIs:

using var client = new HttpClient();
var response = await client.GetStringAsync("https://ziggyrafiq.com");
Console.WriteLine(response. Substring(0, 100));

Cross-Platform Improvements


Improved Linux Support

.NET 8 supports Linux better, improving compatibility and performance for Linux-based .NET applications.

Native Apple Silicon Support

Newer Macs are supported natively with Apple Silicon processors for optimal performance:

 if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    // Check if running on Apple Silicon (ARM64) or Intel (x64)
    if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
    {
        Console.WriteLine("Running natively on Apple Silicon!");
    }
    else
    {
        Console.WriteLine("Running on macOS (Intel chip)!");
    }
}
// Check if the application is running on Windows
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
    Console.WriteLine("Running on Windows!");
}
else
{
    Console.WriteLine("Running on an unsupported OS!");
}
     

Summary

.NET 8 introduces significant improvements in performance, language features, and cross-platform capabilities. Developers can optimize application performance, improve code quality, and ensure compatibility across a variety of environments by leveraging these new features and optimizations. The .NET 8 platform offers powerful new language features in C# 12, creating a strong and flexible foundation for modern software development.

Please check out my GitHub repository for the source code of this article. If you found this article useful, please follow me on LinkedIn https://www.linkedin.com/in/ziggyrafiq/ and like it. My heartfelt thanks go out to you for your support.


Recommended Free Ebook
Similar Articles
Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.