.NET/C# Public Fields vs Properties
I won't argue when to use what, since I honestly don't have enough experience to have being pushed into properties instead of public fields (variables). I haven't had any issues with interfaces or inheritance yet to sway me either way. So far I only see a point in encapsulation and will for reference sake do an example of both.
Public Field:
public string _publicString;
// Does what you expect when the needs are simple, accessible outside the class.
Public Property:
public string _publicString { get; set; }
// Same result, but indirectly through accessor methods.
Public/Private Property:
public string _publicString { get; private set; }
In the last example
_publicString
can only be set privately, but be read publicly. This gives sense of more control
of the encapsulation of your class. But the world won't end by using a public field either IMO when used carefully. I understand
by brief research that certain interface and inheritance creation/usage may force usage of either method, without having digged
more into it. If that's not a problem, it's just personal preference (or pedantism) that decides what to use.More sample code
class SMTP
{
public string server { get; private set; }
public string port { get; private set; }
public string brukernavn { get; private set; }
public string passord { get; private set; }
public SMTP()
{
server = "";
port = "";
brukernavn = "";
passord = "";
}
}