15

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

Community
  • 1
  • 1
Akshay
  • 171
  • 1
  • 1
  • 9
  • 3
    Actually this can be answered easily by google, here's a stackoverflow answer: http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Sercan Ozdemir Apr 29 '15 at 08:02
  • 1
    [Jon has something to say](http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx) – Sriram Sakthivel Apr 29 '15 at 08:02
  • 2
    Good question. But not a good question for Stack Overflow. And also, a question that can be answered a lot better by research rather than asking on a Q&A site or a forum :)) – Luaan Apr 29 '15 at 08:07

4 Answers4

15

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;
      }
      ..
      ..
}
Mehrzad Chehraz
  • 5,092
  • 2
  • 17
  • 28
7

Why do create private variables first and then make properties out of it? Why not a single step?

You use a private variable when you want to do some sort of validation before setting the property, or basically abstract away what is happening inside your class with regards to that property. For example, if you want a given variable to be in a 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 'get' and 'set' and why two approaches to use it?

C#-3.0 brought Auto-Properties, because MSFT saw that alot of people use properties for the "possibility the one day i'll want to validate my variables or change the internal implementation". Exposing a property instead of a variable allows you to add any code validation later, without breaking existing "contract" with any caller of the property.

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

  • There's more fine-grained access control with properties.
  • Need it to be publicly gettable but really only want it set with protected access? No problem (from C# 2 onwards, at least).
  • Want to break into the debugger whenever the value changes? Just add a breakpoint in the setter.
  • Want to log all access? Just add logging to the getter.
  • Properties are used for data binding; fields aren't.
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
3

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

The reason for Property is to create abstraction over internal state of the class. If you for example use public field, you don't have a chance to change it without change Interface of the class. With property you hide the implementation and for rest of the code doesn't change anything. Example:

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

I want to change implementation detail to store/retrieve the 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 changed dramatically but the class interface is still the same.

Aik
  • 3,528
  • 3
  • 19
  • 20
3

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

public class Example
{
   private String _data;

   public String GetData()
   {
      return _data;
   }
}

With properties you can do the same thing in this way:

public class Example
{
   private String _data;

   public String Data { get; private set}       

}

You have shorten your code and made it more clean and you have total control of the field accesibility, but properties has a lot of advantages. For example suppose that you need some logic on your private field, suppose the property is accessed from 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 is not assigned yet you will get a null exception somewhere in your code if you try to use it, but you can implement some logic at avoid it like this:

public class Example
{
   private MyCustomClass _data;

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

So you can implement logic as well with properties.

Moreover remember that when you are creating a property like this

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

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

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



Lastly suppose that in future you need to change the logic of setting value to that field, if you have used public field you will have a lot of work to do but if you used properties you will only have to change the logic of the property and you are done so maintainability is also a good pro of properties!

EDIT
I fogot about Binding most of the frameworks use properties for binding prupose

Sid
  • 14,176
  • 7
  • 40
  • 48
  • "The internal logic of a class should be kept hidden from the outside." Bingo. Use a public property or method. (Java frequently has public getter/setter methods.) Don't publicly expose class variables. Better yet, use interfaces. – Mike Lowery Feb 16 '21 at 20:46