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

Why do we create a private variable inside the class and then make it public property in the following lines in C #? Also I don't understand how to get and set the property.

I mean why do we do this

 public class MyClass
    {
        private string _myProperty;

        public string MyProperty
        {
           get
           { return _myProperty; }
           set
           { _myProperty = value; }
    }

      

or

public class MyClass
{
    public string MyProperty {get;set;}
}

      

My question is very 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. Someone please clarify:

  • Why create private variables first and then make public properties? Why not take one step?
  • What do we need to "get" and "install"? why two approaches to using it, what are the differences?

The answer to the question may be too long. But even if you take your precious time to explain one point correctly, I will be more than obliged. Thanks in advance:)

+3


source to share


4 answers


Why create private variables first and then create properties from This? Why not take one step?

You use a private variable when you want to do some kind of validation before setting a property, or basically abstract what is going on inside your class regarding that property. For example, if you want the given variable to be in the range:

private int foo;
public int Foo 
{
    get { return foo; }
    set 
    {
        if (value < 0 || value > 10)
        {
            throw new ArgumentOutOfRangeException(value);
        }

        foo = value;
    }
}

      

What do we need to "get" and "install" and why two approaches to using it?



C # -3.0 brought Auto-Properties because MSFT saw a lot of people use properties for "the ability I want one day to check my variables or change internal implementation." Exposing a property instead of a variable allows you to subsequently add any code validation without breaking the existing "contract" with any caller of the property.

@JonSkeet spells it beautifully, laid out in his C # In Depth (Thanks @Sriram):

  • Smaller access control with properties.
  • Do you need to publicly retrieve this, but really want it installed with secure access? No problem (since C # 2 at least).
  • Want to enter the debugger when the value changes? Just add a breakpoint to the setter.
  • Want to register all access? Just add logging to the recipient.
  • Properties are used for data binding; no fields.
+6


source


Both examples are equivalent. The second is syntactic sugar for the first.

The reason for Property is to create an abstraction over the internal state of the class. If you are using a public field, for example, you have no way to change it without changing it. Class interface. With a property, you hide the implementation, and for the rest of the code, it doesn't change anything. Example:

public class MyClass
{
    public string MyProperty {get;set;}
}

      



I want to change implementation details to save / get value directly from db

public class MyClass
{
    public string MyProperty {
        get{_db.GetValue('myFiled');}
        set{_db.SetValue('myField', value)}}
}

      

As you can see, the implementation has changed a lot, but the class interface is still the same.

+3


source


Making a field private and exposing it as a property gives the class the ability to manipulate the set and perform operations, which can be useful in a variety of scenarios.

Check

The class can validate the supplied data before storing it in 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 cases, the object field may not be meaningful. Providing a getter method allows the object to communicate this to the client.

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 restricting access to the installer

Another advantage of using properties instead of fields is that it allows the object to restrict access to the field. In the previous example, we had a method without a setter. Another use of this approach is to restrict access to the installer.

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 advantage of this approach is that it allows the class to do some action when the property changes from within the class.

Raising events

A common pattern used to raise XXXXChanged events is to check the value in the setter and raise the event if it has 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 to implement the INotifyPropertyChanged interface.

Models without logic

Even if you don't need any of the things that can be achieved with properties, and you have a class without logic, it would be best practice not to expose the class fields to the outside world of the class. In this case, you can simply use the automatic properties as a shortcut to follow best practice, without directly defining the field.

class UserModel {
      public string Username {
           get;
           set;
      }
      public DateTime Birthdate {
           get;
           set;
      }
      ..
      ..
}

      

+3


source


The internal logic of the class must be hidden from the outside.
Suppose you need a field that can be accessed externally, but can only be set inside the class, without properties you would need to do something like this:

public class Example
{
   private String _data;

   public String GetData()
   {
      return _data;
   }
}

      

You can do the same thing with properties:

public class Example
{
   private String _data;

   public String Data { get; private set}       

}

      

You have to shorten your code and make it cleaner , and you have complete control over the field's availability, but properties have many advantages . For example, suppose you need logic in your private field, suppose the property is accessed from the outside before the field is even assigned. Consider the following example:

public class Example
{
   private MyCustomClass _data;

   public MyCustomClass Data { get { return _data }; private set { _data = value;}}       

}

      

If _data hasn't been assigned yet, you'll get a NULL exception somewhere in your code if you try to use it, but you can implement some logic to avoid that:

public class Example
{
   private MyCustomClass _data;

   public MyCustomClass Data
   { 
      get
      {
         if(_data == null)
           _data = new MyCustomClass();
         return _data;
      }
      private set { _data = value;} }             
}

      

This way you can implement logic with properties.

Also, remember that when you create a property like

public class Example
{
   public String MyData{ get; set;}
}

      

Actually, when you compile it, the compiler translates it to something like this:

public class Example
{
   private String _myData;
   public String MyData{ get {return _myData}; set { _myData = value}}
}

      



Finally, suppose in the future you need to change the logic of the parameter value for that field, if you used a public field, you will need a lot of work, but if you used properties, you only need to change the logic of the property, and you made it maintainability is also a good pro properties!

CHANGE
I fogot of the Binding . Most frameworks use properties to bind prupose

+2


source







All Articles