25: Super 8

17 Nov 2023

Like everybody else we're looking forward to all the new and improved features in .NET 8.

In this episode we're going to rattle through a few of things that have caught our attention.

Random fact

22 Fun Facts About Number 8: Unveiling the Secrets - Amazing Facts Home

  • The digit 8 is formed by two circles or loops, making it visually symmetrical and pleasing to the eye.
  • The number 8 is considered lucky in many cultures, including Chinese and Japanese
  • Eight is the highest digit in the octal numeral system, making it a powerful and significant number.
  • In mathematics, the number 8 is a perfect cube, as it can be expressed as 2 raised to the power of 3
  • In music, an octave is a musical interval spanning eight notes.|
  • The atomic number of oxygen, a crucial element for sustaining life, is 8.

Introduction

What’s new in .NET 8!!

.NET 8 RC2 is available and .NET 8 should launch between Nov 14-16 at .NET Conf 2023 - so it will probably be available by the time you’re listening to this - let us what you think of it.

Let’s see what’s coming in .NET 8

More info can be found here - What's new in .NET 8 | Microsoft Learn, ASP.NET Core updates in .NET 8 Release Candidate 1 - .NET Blog (microsoft.com) and here Performance Improvements in ASP.NET Core 8 - .NET Blog (microsoft.com)

There’s quite a few of them so we’re going rattle through them - this is by no means a definite list there’s loads of stuff!

.Net 8 covers:

  • AspNet 8 (aka AspNet Core 8),
  • C# 12 (released as part of the overall .Net 8 release)
  • .Net 8

ASP.NET Core 8 updates

Untitled

Improved debugging (I remember seeing James Newton-King posting about this as they were working on it…) .Net 7:

.Net 8:

.Net 7:

.Net 8:

Securing Swagger Endpoints

  • Swagger UI endpoints can now be secured in production environments by calling app.MapSwagger().RequireAuthorization();

Blazor

What's new in ASP.NET Core 8.0 | Microsoft Learn

  • New Blazor Web App template
  • Persist component state in a Blazor Web App
  • Form handling and model binding
  • Enhanced navigation and form handling
  • Streaming rendering
  • Inject keyed services into components - more on this later
  • Access **HttpContext as a cascading parameter
  • Render Razor components outside of ASP.NET Core
  • Sections support
  • Error page support
  • QuickGrid - nice!!
  • Route to named elements
  • Root-level cascading values
  • Virtualize empty content
  • Close circuits when there are no remaining interactive server components
  • Monitor SignalR circuit activity
  • Faster runtime performance with the Jiterpreter
  • Blazor WebAssembly debugging improvements
  • Support for dialog cancel and close events
  • Blazor Identity UI

These are just a few of the new features and improvements in Blazor for .NET 8. For more detailed information, you can refer to the official documentation and the release notes provided by Microsoft.

Minimal Apis

  • Binding to forms with [FromForm] attribute now supported
  • Antiforgery middleware service registration in DI with: builder.Services.AddAntiforgery();
  • Support for AsParameters and automatic metadata generation for request and response types:
app.MapPost("/todos", ([AsParameters] CreateTodoArgs payload) =>
{
	if (payload.TodoToCreate is not null)
	{
		return payload.TodoToCreate;
	}
	return new Todo(0, "New todo", DateTime.Now, false);
});

Loads of AOT work to get Minimal Apis working with AOT, eg)

Request delegate generator

  • The RDG translates the various MapGet(), MapPost(), and calls like them into RequestDelegate at compile time
  • Introduced to support native AOT and is enabled by default
  • RDG can be manually enabled even when not using native AOT by setting true
  • This can be useful when initially evaluating a project's readiness for native AOT, or to reduce the startup time of an app.

Smaller bits and pieces

  • Support for named pipes in Kestrel
  • HTTP/3 enabled by default
  • HTTP/2 over TLS (HTTPS) support on macOS
  • SignalR - Specify server timeout and keep alive interval settings using the HubConnectionBuilder
  • HTTP_PORTS and HTTPS_PORTS config support
  • Warning when specified HTTP protocols won’t be used

What's new in C# 12

Primary constructors

  • You can add parameters to a struct or class declaration to create a primary constructor. Primary constructor parameters are in scope throughout the class definition
  • Like you can already do with Record types
  • It's important to view primary constructor parameters as parameters even though they are in scope throughout the class definition
  • Every other constructor for a class must call the primary constructor, directly or indirectly, through a this()

Collection expressions

  • New terse syntax to create common collection values
  • Inlining other collections into these values is possible using a spread operator ... - like typescript
// Create an array:
int[] a = [1, 2, 3, 4, 5, 6, 7, 8];

// Create a span
Span<int> b  = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'];

// Create a jagged 2D array:
int[][] twoD = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

// Create a jagged 2D array from variables:
int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[][] twoDFromVariables = [row0, row1, row2];

Inline arrays (more for framework developers, internal .Net stuff)

  • Inline arrays enable a developer to create an array of fixed size in a struct type
  • used by the runtime team and other library authors
  • An inline array is declared similar to the following struct:
[System.Runtime.CompilerServices.InlineArray(10)]
public struct Buffer
{
    private int _element0;
}

//then used like this

var buffer = new Buffer();
for (int i = 0; i < 10; i++)
{
    buffer[i] = i;
}

foreach (var i in buffer)
{
    Console.WriteLine(i);
}

Optional parameters in lambda expressions

  • You can now define default values for parameters on lambda expressions
  • The syntax and rules are the same as adding default values for arguments to any method or local function

ref readonly parameters (parameter modifiers)

  • C# added in parameters as a way to pass readonly references. in parameters allow both variables and values, and can be used without any annotation on arguments.
  • The addition of ref readonly parameters enables more clarity for APIs that might be using ref parameters or in parameters

Alias any type

  • You can use the using alias directive to alias any type, not just named types
  • That means you can create semantic aliases for tuple types, array types, pointer types, or other unsafe types

Experimental attribute

Interceptors - made for AOT

  • An interceptor is a method that can declaratively substitute a call to an interceptable method with a call to itself at compile time
  • This substitution occurs by having the interceptor declare the source locations of the calls that it intercepts
  • Interceptors provides a limited facility to change the semantics of existing code by adding new code to a compilation, for example in a source generator
  • Use case - AOT to replace in native versions of methods

.NET 8 stuff

**System.Text.Json**

Many improvements have been made to System.Text.Json serialization and deserialization - What's new in System.Text.Json in .NET 8 - .NET Blog (microsoft.com)

  • required and init member support
  • Disabling reflection defaults
  • Size reduction
  • Populate read-only members
  • Missing member handling
  • [JsonNamingPolicy](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonnamingpolicy?view=net-8.0&preserve-view=true#properties) includes new naming policies for snake_case (with an underscore) and kebab-case (with a hyphen) property name conversions.
  • Interface hierarchy support
  • Built-in support for HalfInt128 and UInt128
  • Built-in support for Memory<T> and ReadOnlyMemory<T>
  • Single-usage - JsonSerializer.Serialize<MyPoco>(value, new JsonSerializerOptions { WriteIndented = true });- JsonSerializerOptions (metadata cache is calculated on every serialization) analyzer - performance - analyzer CA1869 which will emit a relevant warning whenever it detects single-use options instances.
  • Extend JsonIncludeAttribute and JsonConstructorAttribute support to non-public members

Keyed DI services What's new in .NET 8 | Microsoft Learn

Keyed dependency injection (DI) services provides a means for registering and retrieving DI services using keys. By using keys, you can scope how your register and consume services. These are some of the new APIs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<BigCacheConsumer>();
builder.Services.AddSingleton<SmallCacheConsumer>();

builder.Services.AddKeyedSingleton<IMemoryCache, BigCache>("big");
builder.Services.AddKeyedSingleton<IMemoryCache, SmallCache>("small");

Hosted lifecycle services (What's new in .NET 8 | Microsoft Learn)

Hosted services now have more options for execution during the application lifecycle. IHostedService provided StartAsync and StopAsync, and now IHostedLifecycleService provides these additional methods:

Summary of .NET 8

From https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8

There is so much coming in .NET 8 - to much to list here! MS has some great documentation about it all and there’s lots of people doing youtube videos to demo some of the new stuff.

We’re (hopefully) going to do some youtube shorts about some of the .NET 8 features - they’ll be available on our youtube channel dotnetrambles (there’s not much there at the moment!)

OS project/utility of the week

Notepad++ (notepad-plus-plus.org) is a free and open-source text editor that is designed for programmers. It offers a wide range of features, including syntax highlighting, code folding, autocompletion, and multi-view editing. Notepad++ supports a variety of programming languages and provides a user-friendly interface with customizable themes and layouts. It also supports plugins, allowing users to extend its functionality. Notepad++ is known for its speed, efficiency, and ease of use, making it a popular choice among developers.