roslyn: The default parameter value for struct and record struct is ignored when a new instance is created

Creating a new structure value via new() automatically and unconditionally replaced by using default() without taking into account the presence or absence of a default value for the parameter

There is no warning about the issue, and the syntax itself is quite acceptable.

There is no such issue for class because there is no such transformation there.

Version Used: .NET 8 RTM SDK

Steps to Reproduce:

using System;

RStruct rStruct = new();
RStructMulti rStructMulti = new(2);
S s = new();
R r = new();

Console.WriteLine($"{rStruct.A}, {rStructMulti.A}, {s.A}, {r.A}");

record struct RStruct(int A = 42);
record struct RStructMulti(int B = 4242, int A = 42);

struct S {
    public S(int a = 42) => A = a;

    public int A { get; }
}

record R(int A = 42);

SharpLab Link

Expected Behavior:

42, 42, 42, 42

Actual Behavior:

0, 42, 0, 42

RStruct rStruct = default(RStruct);
RStructMulti rStructMulti = new RStructMulti(2);
S s = default(S);
R r = new R(42);

About this issue

  • Original URL
  • State: closed
  • Created 7 months ago
  • Comments: 21 (12 by maintainers)

Most upvoted comments

It’s a regret, but unfortunately I’m not surprised - over the past years in working with C# I’ve already understood the general approach.

I can only wish you good luck with further development of the compiler!

I agree that it worths an analyzer to hint user for this situation. It’s somehow counter-intuitive.

This should be expected, because parameterless constructor is always treated as defined, and will take precedence in overloading.

You can add a real parameterless constructor starting from C# 10.