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?
Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers. A field can optionally be declared static.
public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final .
Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private.
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.
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.
What is the best practice for using public fields?
“Don’t.” See also: Should protected attributes always be banned? which concerns protected fields but what is said there is even more true for public ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With