Visual Studio recommends that you use a read-only property to simplify and/or improve the code written based on certain algorithms that takes in consideration different common and standard coding techniques to create clean, reduced, robust and optimized code.
Here, the goal is to replace both the read-only property that gets the value of the private field without doing anything else, and that private field.
So, if you accept the relevant suggestion in the list for this case (I have several with VS2017), you will get the written code automatically simplified for you in case you select the choice "Use auto-property" in the suggested options to change the code (others are certainly not relevant):
public class Foo
{
public int MyNum { get; }
public Foo (int num)
{
MyNum = num;
}
}
This is a correct suggestion and accepting it is suitable.
Others suggestions produces things you will in most cases not need...
If you plan to add behaviors in the getter, you can ignore this suggestion from Visual Studio:
public class Foo
{
public int MyNum
{
get
{
return _myNum >= 100 ? 100 : _myNum;
}
}
private readonly int _myNum;
public Foo(int num)
{
_myNum = num;
}
}
Otherwise if you want a read only data member, you can use a read-only field:
public class Foo
{
public readonly int MyNum;
public Foo (int num)
{
MyNum = num;
}
}
C# readonly vs Get
Readonly field vs. readonly property
Which is better between a readonly modifier and a private setter?
What is the difference between a field and a property?
But if you need this data member being a property, for example to be used in serialization or by the Visual Studio Designers and Helpers, and it must be writable in general... and if you use C# 9+, you can use an init-only property:
public class Foo
{
public int MyNum { get; init; }
public Foo (int num)
{
MyNum = num;
}
}
What is difference between Init-Only and ReadOnly in C# 9?
Also and before C# 9, without a get-only auto-property, to have a property coupled with a private field, and to remove the Visual Studio refactoring assitant suggestion, without disabling this module, you can simply use a classic getter method to avoid the Visual Studio code refactoring suggestion:
public class Foo
{
private readonly int _myNum;
public int GetMyNum() => _myNum;
public Foo(int num)
{
_myNum = num;
}
}