Primary Constructors in C# 12
With c# 12 (.Net 8), we finally get primary constructors for classes and structs. I’ve wanted primary constructors since I started working in Typescript in 2016. Typescript had them from the beginning. I never understood why we did not have them in c#. To be fair, primary constructors were introduced with record type in c# 9. It was like Microsoft was teasing me.
Current way, without primary constructors
public class BankAccount
{
public BankAccount(string accountID, string owner)
{
AccountID = accountId;
Owner = owner;
}
public string AccountID { get; }
public string Owner { get; }
public override string ToString() => $"Account ID: {AccountID}, Owner: {Owner}";
}
With primary constructors
public class BankAccount(string accountID, string owner)
{
public string AccountID { get; } = accountID;
public string Owner { get; } = owner;
public override string ToString() => $"Account ID: {AccountID}, Owner: {Owner}";
}