Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we create a private variable inside a class and then set property?

Tags:

c#

.net

oop

class

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 :

  • Why do create private variables first and then make public properties out of it? Why not a single step?
  • What do we need 'get' and 'set'? why two approaches to use it, what are the differences?

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 :)

like image 478
Akshay Avatar asked Apr 29 '15 07:04

Akshay


People also ask

Why do we make variables private in classes?

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.

Why we use properties instead of public variables?

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.

What is the use of private variable in Java?

The private keyword is an access modifier used for attributes, methods and constructors, making them only accessible within the declared class.

What is the point of private variables in C#?

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.


1 Answers

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.

Validation

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();
             }
         }
      }
      ..
      ..
}

Invalid field value

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;
        }
    }
}

Not providing a setter, or limiting access to the setter

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.

Raising events

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.

Logic-less models

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;
      }
      ..
      ..
}
like image 194
Mehrzad Chehraz Avatar answered Sep 23 '22 21:09

Mehrzad Chehraz