Why do we create a private variable inside a class and then make a public property out of it on the following lines in c#? Also I do not get the concept of getting and setting a property.
I mean why do we do this
public class MyClass
{
private string _myProperty;
public string MyProperty
{
get
{ return _myProperty; }
set
{ _myProperty = value; }
}
or this
public class MyClass
{
public string MyProperty {get;set;}
}
My question is much similar to this one: Why do we need to create class variables to get and set a property?
The above thread didn't seem to solve my problem. Somebody, please elaborate on :
The question's answer might be too long. But even if you spend your valuable time just to explain a single point properly, I'll be more than obliged. Thanks in advance :)
Making a variable private "protects" its value when the code runs. At this level, we are not concerned with protecting it from other programmers changing the code itself. The point of so-called "data hiding" is to keep internal data hidden from other classes which use the class.
Property always a better choice instead of public variables. Property is safe while public variables are unsafe. And you can not debug with public variables but you can do that with property. Public variables are useful.
The private keyword is an access modifier used for attributes, methods and constructors, making them only accessible within the declared class.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
Making a field private and exposing it as a Property gives the class power of controlling set and get operations, this can be useful in different scenarios.
The class can validate provided data before storing it into the field:
class WeatherInfo {
private static readonly int minDegree = -273;
private static readonly int maxDegree = 75;
private int degree;
public int Degree {
get {
return this.degree;
}
set {
if (value < minDegree || value > maxDegree) {
throw new ArgumentOutOfRangeException();
}
}
}
..
..
}
In some circumstances, a field of an object may not have a meaningful value. Providing a getter method, allows the object to inform it's client about that.
class User {
private DateTime loginTime;
private bool loggedIn;
..
..
public DateTime LoginTime {
get {
if (!this.loggedIn) {
throw new InvalidOperationException();
}
return loginTime;
}
}
}
Another benefit of using properties instead of fields is that it allows the object to limit access to the field. In the previous example we had a method without a setter. Another use of this approach is limiting access to the setter.
class Customer {
private string name;
private string family;
private string nameFamily;
public string name {
get {
return this.name;
}
private set {
if (!string.Equals(name, value)) {
this.name = value;
this.UpdateNameFamily();
}
}
}
private void UpdateNameFamily() {
this.nameFamily = string.Format("{0} {1}", this.name, this.family);
}
..
..
}
as you can see, the benefit of this approach is it allows the class to perform some action when the property gets changed from inside of the class.
A common pattern used to raise XXXXChanged events is checking the value in the setter and raise a event if it is changed:
class Question {
public event EventHandler AnsweredChanged;
private bool isAnswered;
..
..
public bool IsAnswered {
get {
return this.isAnswered;
}
set {
if (this.isAnswered != value) {
this.OnIsAnsweredChanged();
}
}
}
private void OnIsAnsweredChanged() {
if (this.AnsweredChanged!= null) {
this.AnsweredChanged(this, EventArgs.Empty);
}
}
}
Another common use of this approach is implementing INotifyPropertyChanged interface.
Even if you don't need none of what can be achieved by properties, and you have a logic-less class it has been a best practice to not to expose class fields to outside world of the class. In that case, you can simply use auto-properties as the shortcut way to follow the best practice, without directly defining a field.
class UserModel {
public string Username {
get;
set;
}
public DateTime Birthdate {
get;
set;
}
..
..
}
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