Introduction
.NET 9, succeeding .NET 8, places particular emphasis on cloud-native applications and enhancing performance. It will receive standard-term support (STS) for 18 months. You can download .NET 9 here.
Serialization
In System.Text.Json, .NET 9 has new options for serializing JSON and a new singleton, making it easier to serialize using web defaults.
-
Indentation options
var options = new JsonSerializerOptions
{
WriteIndented = true,
IndentCharacter = '\t',
IndentSize = 2,
};
string json = JsonSerializer.Serialize(
new { Value = 1 },
options
);
Console.WriteLine(json);
//{
// "Value": 1
//}
JsonSerializeOptions includes new properties that let you customize the indentation character and indentation size of written JSON as given above.
-
Default web options
string webJson = JsonSerializer.Serialize(
new { SomeValue = 42 },
JsonSerializerOptions.Web // Defaults to camelCase naming policy.
);
Console.WriteLine(webJson);
// {"someValue":42}
If you want to serialize with the default options that ASP.NET Core uses for web apps, use the new JsonSerializeOptions.Web singleton.
LINQ
Recently added to the toolkit are the CountBy and AggregateBy methods. These functions enable state aggregation by key, eliminating the necessity for intermediate groupings through GroupBy.
CountBy allows for swift computation of the frequency of each key. In the following example, it identifies the word that appears most frequently within a given text string.
string sourceText = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed non risus. Suspendisse lectus tortor, dignissim sit amet,
adipiscing nec, ultricies sed, dolor. Cras elementum ultrices amet diam.
""";
// Find the most frequent word in the text.
KeyValuePair<string, int> mostFrequentWord = sourceText
.Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(word => word.ToLowerInvariant())
.CountBy(word => word)
.MaxBy(pair => pair.Value);
Console.WriteLine(mostFrequentWord.Key);
AggregateBy provides the capability to execute broader, more versatile workflows. Illustrated in the following example is the calculation of scores associated with a specified key.
(string id, int score)[] data =
[
("0", 42),
("1", 5),
("2", 4),
("1", 10),
("0", 25),
];
var aggregatedData =
data.AggregateBy(
keySelector: entry => entry.id,
seed: 0,
(totalScore, curr) => totalScore + curr.score
);
foreach (var item in aggregatedData)
{
Console.WriteLine(item);
}
//(0, 67)
//(1, 15)
//(2, 4)
Cryptography
In the realm of cryptography, .NET 9 introduces a new one-shot hash method within the CryptographicOperations type. .NET offers various static "one-shot" implementations of hash functions and related functions, such as SHA256.HashData and HMACSHA256.HashData. Utilizing one-shot APIs is preferred due to their potential to optimize performance and minimize or eliminate allocations.
When a developer aims to create an API supporting hashing with the caller defining the hash algorithm, it typically involves accepting a HashAlgorithmName argument. However, employing this pattern with one-shot APIs necessitates switching over every potential HashAlgorithmName and subsequently utilizing the appropriate method. To address this issue, .NET 9 introduces the CryptographicOperations.HashData API. This API enables the generation of a hash or HMAC over an input as a one-shot operation, with the algorithm determined by a HashAlgorithmName.
static void HashAndProcessData(HashAlgorithmName hashAlgorithmName, byte[] data)
{
byte[] hash = CryptographicOperations.HashData(hashAlgorithmName, data);
ProcessHash(hash);
}
Conclusion
.NET 9 introduces significant enhancements tailored for cloud-native applications and performance optimization. With a focus on serialization, LINQ improvements, and advancements in cryptography, developers can leverage new features and APIs to streamline development processes and enhance application security. Notable additions include enhanced JSON serialization options, powerful LINQ methods like CountBy and AggregateBy, and convenient CryptographicOperations.HashData API for efficient hashing operations. As .NET 9 continues to evolve, it promises to empower developers with robust tools and capabilities to build modern, high-performing applications for diverse use cases.
References
- Microsoft. ".NET 9 Documentation."
Thank You, and Stay Tuned for More