0

This is my C# code:

record struct recName(int A) { }

And this is generated code behind the scenes:

internal struct recName : IEquatable<recName>
{
    public recName(int A)
    {
        <A>k__BackingField = A;
    }

    private int <A>k__BackingField;
    public int A
    {
        get { return <A>k__BackingField; }
        set { <A>k__BackingField = value; }
    }
}

Why structs properties generated with get/set properties, but type declared with same syntax like this is generated as a 'get/init'. record class recName(int A) { }:

internal class recName : IEquatable<recName>
{
    public recName(int A)
    {
        <A>k__BackingField = A;
    }

    private readonly int <A>k__BackingField;
    public int A
    {
        get
        {
            return <A>k__BackingField;
        }
        init
        {
            <A>k__BackingField = value;
        }
    }
}

I cant understand why 'record struct' cant contain get/init property?

3
  • 1
    Record structs can contain get/init properties. You can try declaring one yourself. It's just that the parameters in the primary constructor does not generate get/init properties, but get/set properties instead. If you want to ask why they don't generate get/init properties, please clarify what kind of answer you want first. Commented Sep 14, 2024 at 14:07
  • 4
    Short answer, this is by design: learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Use readonly record struct if you want the read-only behavior in your record struct. Commented Sep 14, 2024 at 14:11
  • 2
    Also, note that the parameters in the primary constructor does generate get/init properties for a readonly record struct. Commented Sep 14, 2024 at 14:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.