Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make primary constructor parameters readonly?

Tags:

c#

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?

like image 269
Daan Avatar asked Sep 02 '25 16:09

Daan


1 Answers

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.

like image 118
Searles Avatar answered Sep 04 '25 06:09

Searles