Auto Properties in C# 6.0
C# 6.0 brings the ability to initialize an auto-properties pretty much like the way we do for a field. This helps you to intialize the backing field without woking through the setter of the auto property or making using of a local variable. It's executed in the order as written and not at the time when the object is initialized. It means that we cannot reference it using this keyword since the property iniitialization happens before the object intialization.
In the earlier versions, suppose if we want to initialize the properties to some default values we were doing that at the time of instantiating an object as shown below
In C# 6.0, now it's possible to initialize the values for the properties at the time of declaration itself.
Many of you may be wondering why I am using a $ symbol in front of the string and how can I use the C# syntax inside the string which is later transformed into the correct message during execution of the code. It's the new String interpolation feature in C# 6.0 and you read more about it here.
And you can mix and match the defaults with the ones you want as shown below. In this example, I have modified the default values at the time of instantiation for FirstName and LastName properties and left the Email property untouched
Also we can initialize it without a setter also.
No Comments
Connecting Azure Blob Storage account using Managed Identity
Posted 12/9/2022Securing Azure KeyVault connections using Managed Identity
Posted 11/26/2022Manage application settings with Azure KeyVault
Posted 11/9/2022Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020