When I write a class I always expose private fields through a public property like this:
private int _MyField; public int MyField { get{return _MyField; }
When is it ok to just expose a public field like this:
public int MyField;
I am creating a structure called Result and my intention is do this:
public Result(bool result, string message) { Result = result; Message = message; } public readonly int Result; public readonly int Message;
What is the best practice? Is it ever ok to do this?
I only ever expose public fields when they’re (static) constants – and even then I’d usually use a property.
By ‘constant’ I mean any readonly, immutable value, not just one which may be expressed as a ‘const’ in C#.
Even readonly instance variables (like Result and Message) should be encapsulated in a property in my view.
See this article for more details.