It may be that .NET 5, the one and only .NET that will clear the confusion and lead the way for the next years was probably the biggest(?) announcement of Microsoft Build 2020, but there were numerous other equally important; from the general availability of the Blazor WebAssembly, the Azure Static Web Apps and all the projects related to IoT and Artificial Intelligence, all the way to .NET MAUI (short for Multi-platform App UI), Visual Studio CodespacesEntity Framework Core 5Project TyeAzure Quantum and the multiple new features and capabilities of Azure Cosmos DB.

Although there were many more interesting things, C# 9 was left out intentionally because in this post we will deal with some of its exciting new features!

init accessor

Up until C# 9, in order to use the object initializer syntax the properties of that object had to be mutable, which means they could change anywhere in the code even after object initialization. In other words, there was no way to use object initilizer on immutable properties, or even better a property had to be publicly accessible to use object initializer:

//In C# 8, a mutable object like the following allowed object initializer syntax
	public class Person
	{
	    public string FirstName { get; set; }
	    public string LastName { get; set; }
	}

	//A new instance of "Person" using object initializer syntax
	new Person
	{
	    FirstName = "George",
	    LastName = "Kosmidis"
	}

	//An attempt to use object initializer to create an instance in the following object would result in error
	public class Person
	{
	    public string FirstName { get; private set; }
	    public string LastName { get; }
	}
	// CS0272 The property or indexer 'Person.FirstName' cannot be used in this context because the set accessor is inaccessible
	// CS0200 Property or indexer 'Person.LastName' cannot be assigned to -- it is read only

The init accessor comes to solve this problem, by allowing the object initializer syntax but no field mutation after initialization:

	//In C#9 you can use the "init" accessor that honours immutability 
	public class Person
	{
	    public string FirstName { get; init; }
	    public string LastName { get; init; }
	}

	//A new instance can be created using object initializer syntax
	var me = new Person
	{
	    FirstName = "George",
	    LastName = "Kosmidis"
	}

	//But a change in a property value will throw an error
	me.FirstName = "NewName";
	// CS0200 Property or indexer 'Person.FirstName' cannot be assigned to -- it is read only

#c# 9 #programming-c #csharp

Some of it exciting new features C# 9.0
1.30 GEEK