.NET 8 Preview 1 - Features

Posted on March 1, 2023
.NET Coredotnetnewreleasedotnet8

.NET 8 is the successor to .NET 7. It will be supported for three years as a long-term support (LTS) release.

You can download .NET 8 Preview 1, for Windows, macOS, and Linux.

After downloading and installing if you don't see the option to select .net 8.0 preview while creating a project

Follow the steps to enable the framework option

  1. Open Visual Studio -> Help -> Check for Update -> Update your Visual Studio 2022
  2. Go to tools -> Options -> Preview Feature -> Check the box below

Options

Preview Feature

  1. Restart the Visual Studio

Here are a few highlights with .NET 8 Preview 1

  1. Publishing assets in Debug
  2. Support for serializing properties from interface hierarchies
  3. JsonNamingPolicy includes new naming policies for snake_case (with an underscore)
  4. New Method introduces in System.Random i.e. GetItems() and Shuffle()
  5. Performance-focused types
  6. .NET 8 includes improvements to code generation and just-in time (JIT) compilation
  7. .NET container images

Download the sample playground code from GitHub

1. Publishing assets in Debug

dotnet publish and dotnet pack commands are intended to produce production assets, they now produce Release assets by default. But with dot Net 8, you will be able to generate assets for Debug as well by by setting the PublishRelease property to false. for e.g

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>dotnet8_playground</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <PublishRelease>false</PublishRelease>
  </PropertyGroup>

</Project>

Here is output

OutPut Of Publish

2. Support for serializing properties from interface hierarchies

The following code shows an example where the properties from both the immediately implemented interface and its base interface are serialized.

public interface IPerson
{
    public int MaxAge { get; set; }
}

public interface IEmployee : IPerson
{
    public DateTimeOffset SalaryRevisionDate { get; set; }
}

public class Employee : IEmployee
{
    public int MaxAge { get; set; }
    public DateTimeOffset SalaryRevisionDate { get; set; }
}
IEmployee employeeObj = new Employee { MaxAge = 35, SalaryRevisionDate = DateTimeOffset.Now };
var jsonString = JsonSerializer.Serialize(employeeObj);

Here is output

Output of JsonSerializer

3. JsonNamingPolicy includes new naming policies for snake_case (with an underscore)

var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
var jsonSnakeString = JsonSerializer.Serialize(employeeObj, options);

Here is output

Output of JsonSerializer

4. New Method introduces in System.Random i.e. GetItems() and Shuffle()

These methods are useful for reducing training bias in machine learning (so the first thing isn't always training, and the last thing is always test).

public static class RandomnessDemo
    {
        private static readonly string[] s_data = { "Red", "Green", "Blue" };

        public static void TestRandomness()
        {
            //Get Item
            string[] result = Random.Shared.GetItems<string>(s_data, 31);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Get Item\n");
            Console.WriteLine("[{0}]\n", string.Join(", ", result));

            //Shuffle
            string[] trainingData = LoadTrainingData();
            Random.Shared.Shuffle(trainingData);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Shuffle\n");
            Console.WriteLine("[{0}]\n", string.Join(", ", s_data));
        }

        public static string[] LoadTrainingData()
        {
            return s_data;
        }
    }

Here is output

random combination of colors output

In the example, it gets a random combination of colors from the defined array and in the second example, it shuffles every time for a new combination.

5. Performance-focused types

The new System.Collections.Frozen namespace includes the collection types FrozenDictionary<TKey, TValue> and FrozenSet. These types don't allow any changes to keys and values once a collection is created. That requirement allows faster read operations (for example, TryGetValue()). These types are particularly useful for collections that are populated on first use and then persisted for the duration of a long-lived service, for example:

private static readonly FrozenDictionary<string, bool> s_configurationData =
    LoadConfigurationData().ToFrozenDictionary(optimizeForReads: true);
// ...
if (s_configurationData.TryGetValue(key, out bool setting) && setting)
{
    Process();
}

7 .NET container images

The container images now use Debian 12 (Bookworm). Debian is the default Linux distro in the .NET container images. To run as non-root, add the following line at the end of your Dockerfile

USER app

Download the sample playground code from GitHub

Here is an official announcement from Microsoft

Thanks for reading!


Posted on March 1, 2023
Profile Picture

Arun Yadav

Software Architect | Full Stack Web Developer | Cloud/Containers

Subscribe
to our Newsletter

Signup for our weekly newsletter to get the latest news, articles and update in your inbox.

More Related Articles