This article presents a small sample how to use implicit index access in object initializers in C# 13, using the 'hat' operator.
This is a very specialized functionality, but it can become handing when you intialize objects and their collection fields and properties.
For example, creating an object with an array and just doing some few adjustments on the collection becomes a bit more accessible.
Let's see some code what this new feature in C# 13 is :
var nums = new[] { 6, 9, 4, 20 };
var lastElement = nums[^1]; //last element via index
Console.WriteLine(lastElement);
var greeter = new Greeter {
Message = {
[^1] = '!'
},
SomeNums =
{
[^1] = 5,
[^2] = 4,
[^3] = 3,
[^4] = 2,
[^5] = 1
}
};
Console.WriteLine(greeter);
Console.ReadKey();
class Greeter
{
public char[] Message { get; set; } = "Hello?".ToCharArray();
public int[] SomeNums = new int[5];
public override string ToString()
{
return $"Message = {string.Join(',', Message)}, SomeNums = {string.Join(',', SomeNums)}";
}
}
This outputs the following :
20
Message = H,e,l,l,o,!, SomeNums = 1,2,3,4,5
We initialize an instance of the class Greeter into the variable greeter and set the fields / properties in the initializer. We already inited the property Message to "Hello?" and at the same type, in the object initalizer, alter the last letter where we use the hat operator
using :
[^1] = '!'
, which results into the string "Hello!". Here we initalized an object in an easy way and at the same time was able to alter the contents of collections of the object, altering in the example the last char of a char array.
We also set the int array one element at a time using again the hat operator here. We could of course not use the hat operator here, which will access the nth last element in a collection. Make note that the hat operator is 1-based, so the last element is
^1
,
the second last element is
[^2]
.
Note that to use C#, you have to download the .NET 9 SDK preview from this url :
https://dotnet.microsoft.com/en-us/download/dotnet/9.0
Make note that you select the .NET 9 SDK for the platform you are using. Most .NET developers on Windows can download x64 SDK for example.
After installing the SDK , go to Tools => Options in VS 2022 and choose Environment : Preview features. Check the option : 'Use previews of .NET SDK'. Restart VS 2022 after doing this.
You can now test out C# 13 and .NET 9 and for example create a console application for .NET projects (not .NET Framework).
The .csproj in my sample code looks like this, make note of the
TargetFramework, set it to
net9.0. Also set the
LangVersion to
Preview.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>Preview</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>