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; }
In general, if an type is going to be used as a data holder, it should either be:
If there is no practical alternative to using a mutable class, the question of whether to expose public fields depends upon whether there's any foreseeable need for any version of the class to include validation logic in a property setter, and also whether the type of a member will be a value type or class type. If Bounds
is a public field of type Rectangle
, an expression like SomeClass.Bounds.Width
can access the Width
of the rectangle without having to access any other members. By contrast, if Bounds
were a property--even a mutable one--that expression would have to copy all four members of Bounds
to a temporary structure, and then access the Width
field of that.
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.
The answer I give is that Properties are more Refactor friendly.
If you have an assembly with read-only fields, then change them to properties. If you have another assembly that I accessing the fields (now properties), they wont work without a compile. Fields and properties are not the same as far as the compiler is concerned.
Back to refactoring, say you started with a property. Now you need to change where the data is coming from (you will access it from another class). If you were dealing with fields you have some hard decisions to make on how to make that happen. Properties are much more forgiving -- because you can hide logic in them.
The best practice is to use properties for several reasons. First, it decouples the API from the underlying data structure. Second, anything built into the framework that binds to objects does to to properties, not fields.
I'm sure there are more reasons, but those two always seem to be enough for me.
What is the difference between a Field and a Property in C#?
I recommend using something similar to this:
public class Result{
public bool Result { get; protected set; }
public string Message { get; protected set; }
public Result(bool result, string message) {
Result = result;
Message = message;
}
}
This way, you don't need to declare member variables, let the compiler do the work for you! The code is very clean and short, and refactoring is a breeze.