Structure types of C# can't use public?

Hi, everyone,

I use SonarLint for Visual Studio 2022 and installed SonarLint in my company.

I don’t understand why properties can’t use public in structure types of C#?
(not class, more similar example in Microsoft Learn)
Why must use private?

example
image

my code
image

Hello @ Chi-Hung_Li,

Rule S1104 is called “Fields should not have public accessibility”. The complaint is about the field being public. To fix the issue, turn your fields into auto-properties:

public struct Coord
{
    public int X { get; } // A struct should be read-only if possible.
    public int Y { get; set; } // Make it read-write only if you know the implications for structs.
}

Another option is to mark your public fields as read-only:

public struct Coord
{
    public readonly int x;
    public readonly int y;
}

Further readings:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.