I'm using C# 12. In C# 12 I can use primary constructor:
Implementation 1 :
public class Calculation(int a,int b)
{
public int Addition() => a + b;
public int Subtraction() => a - b;
}
Implementation 2 :
public class Calculation(int a,int b)
{
private int _a { get; init; } = a;
private int _b { get; init; } = b;
public int Addition() => _a + _b;
public int Subtraction() => _a - _b;
}
When I'm calling this method like :
console.WriteLine(new Calculation(10,25).Addition());
Both implementation working fine, so I'd like to know whether there is any advantage to using the longer Implementation 2 over the shorter Implementation 1.
There is no point in creating fields/properties yourself this way, since the compiler will create them for you in this case (decompilation @sharplab.io).
From the Tutorial: Explore primary constructors doc (they use
struct
but the handling of the primary ctor for classes is basically the same):The potential downside is that the generated field is mutable:
Though your approach does not fix that but introduces some clutter when you can confuse
_a
anda
. There is no way to mark the generated field asreadonly
for now (but there are plans for the feature - see this LDM notes doc and this proposal) but you can shadow the ctor parameter by using field with the same name (or property):See also: