Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting only a setter property

Tags:

c#

I have an object model that has a property like this:

public class SomeModel
{
   public string SomeString { get; set; }

   public void DoSomeWork()
   {
      ....
   }
}

I want the DoSomeWork function to execute automatically after the SomeString property changes. I tried this but it's not working:

public string SomeString { get; set { DoSomeWork(); } }

What's the correct syntax?

like image 496
frenchie Avatar asked Feb 11 '13 14:02

frenchie


People also ask

Can you have a setter without a getter in Python?

Let's write the same implementation in a Pythonic way. You don't need any getters, setters methods to access or change the attributes. You can access it directly using the name of the attributes.

What is a private setter?

Private setter means the variable can be set inside the class in which it is declared in. It will behave like readonly property outside that class's scope.

What will happen if you bind to a property for which no public setter is available?

If no getter or setter for the field exists, a direct access for the field is performed. If a getter exists for the field, it will be executed when trying to read the field from outside.

What is the difference between getter and setter in JavaScript?

Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.


1 Answers

Use a private field instead, like this ...

public class SomeModel
{
    private string someString = "";

    public string SomeString {
        get { return this.someString; }
        set {
            this.someString = value;
            this.DoSomeWork();
        }
    }

   public void DoSomeWork()
   {
      ....
   }
}
like image 187
Gwyn Howell Avatar answered Sep 20 '22 22:09

Gwyn Howell