简体   繁体   中英

Return Nothing in an if statement of a property's setter WPF

What is the flow of the below code snippet? What does return; means? What will it do when return; executes?

public bool ActionSafeAction
{
    get
    {
        return this.ActionSafeAction;
    }

    set
    {
        if (value.Equals(this.ActionSafeAction))
        {
            return;
        }

        if (value)
        {
            this.ActivateItem(this.ActionSafeAction);
            this.ActionSASelected = false;
        }

        this.ActionSafeAction= value;
        this.NotifyOfPropertyChange(() => this.ActionSafeAction);
    }
}

It will do nothing more of what comes after the return . It immediately returns from the setter and doesn't change any underlying value.

Writing ActionSafeAction = true if ActionSafeAction is already true will hit this return statement and not do anything more.

Properties are little more then Syntax Sugar for Get and Set functions. That is what they are designed to be.

Set in paritcular is effectively a function that takes a parameter "value" and returns void. Except for the name and the way you call it, that set is effectively: public void SetActionSafeAction(bool value) . Making getters and setters easily implement and useable - again, that is what Properties are there for.

The return in the if will end the execution of this function, there and then. As it would with any other function that returns void. The rest of the checks and the setting/change notification will not be executed.

I think if we illistruate the getter and setter like below you may understand better. Get and Set are implict definition of two seperated method that effect a particular member.

public class Foo
{
    private string myMember;

    public string GetMyMember()
    {
       return myMeber;
    }

    public void SetMyMember(string value)
    {
       myMember = value;
    }
}

So as you see setter is a actually a void method and when you call return statement at any part of this method it will just leave method without executing rest of the code. This is what happned at your ActionSafeAction propertiy's setter too.

The equal of the above two method will be this property:

public class Foo
{
   private string myMember;

   public string MyMember
   {
      get { return myMember; }
      set { myMember = value; }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM