I am trying to familiarize with the C# 12 primary constructor variables.
Here is my code:
public class BankAccountNew(string accountID, string owner)
{
public void DoSomethingWrong()
{
accountID = "Wrong";
}
}
public class BankAccounOld
{
private readonly string accountID;
private readonly string owner;
public BankAccounOld(string accountID, string owner)
{
this.accountID = accountID;
this.owner = owner;
}
public void DoSomethingWrong()
{
accountID = "Wrong";
}
}
As you can see, I want DoSomethingWrong
cause a compiler error to be triggered as it modifies a parameter I want to be readonly. I succeed in this for BankAccounOld
but this requires me to type a lot of code which is not needed anymore in the latest C# version.
As explained accountID
is supposed to be readonly. How do I change BankAccountNew
to ensure this is recognized as readonly so it triggers a compiler error?
There seems to be a way by declaring the parameter as 'in' in the primary ctor. The following code snippet works:
public class SomeClass(in int param)
{
private readonly int _param = param;
public int GetSum(int other)
{
// Cannot access 'param' here.
return other + _param;
}
}
The primary ctor parameter is now not available in the method but only in the initialization of the private readonly field making it effectively readonly.
EDIT: Writing '++param' in the assignment leads to a compiler error, therefore it is actually really read-only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With