In the Property Setter, this is only useful for setting if the Differs?

I am wondering what advantages this code has:

    private int _TestID;
    public int TestID
    {
        get 
        { 
            return _TestID;
        }
        set
        {
            if(_TestID != value)
            {
                _TestID = value;
            }
        }
    }

      

against. this is:

    private int _TestID;
    public int TestID
    {
        get 
        { 
            return _TestID;
        }
        set
        {
            _TestID = value;
        }
    }

      

It seems to me that this was done in the name of efficiency (only the setup if different), but wouldn't the test take so long (or longer) that the initial set? I'm not sure if I missed something here, but would love to hear any comments and explanations.

+2


source to share


5 answers


This is useful when you combine it with RaisePropertyChanged ("TestID") (inside an if, after setting the field value) which is often found with WPF or other data binding solutions.



class Something : INotifyPropertyChanged
{
      public int TestID 
      {
           get { return testId; }
           set 
           {
                if (testId != value)
                {
                     testId = value;
                     RaisePropertyChangedEvent("TestID");
                }
           }
      }
 }

      

+14


source


This is the type of optimization that I would happily leave in the compiler. I would not like to "force" efficiency, which may or may not be true in every situation.



+1


source


Indeed, I think the first example will cause more problems when it comes to complex types and operator overloading. In this particular case, the first example is pretty pointless.

0


source


If performance is the only issue here, I would pick the former. Even if there is a difference in performance, it will be too small to notice.

This is also an unnecessary expansion of lines of code.

0


source


I think the example code you gave is not entirely correct. Did you mean it?

private int _TestID;
public int TestID
{
    get
    {
        return _TestID;
    }
    set
    {
        if (_TestID != value)
        {
            _TestID = value;
        }
    }
}

      

The reason for this design is also incomprehensible to me. If, however, _TestID is a property instead of an int , then this construct can be useful, since setting _TestID in this case can be an expensive operation.

0


source







All Articles