Getter without body, setter with

I have a property that is currently automatic.

public string MyProperty { get; set; } 

However, now I need it to perform some action every time it changes, so I want to add logic to the setter. So I want to do something like:

 public string MyProperty { get; set { PerformSomeAction(); } } 

However, this does not create ... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial

I cannot just return the getter MyProperty , as this will cause an infinite loop.

Is there a way to do this, or do I need to declare a private variable to be referenced? I would prefer not to use MyProperty through the code both in this class and outside it

+7
c #
source share
5 answers

You need to use the property with the support field:

 private string mMyProperty; public string MyProperty { get { return mMyProperty; } set { mMyProperty = value; PerformSomeAction(); } } 
+8
source share

You cannot implement one without the other, because when using one of them, it refers to the (hidden) support field, which is automatically generated in the case of an auto-generated property. However, when you implement it, you must set this background field in both directions.

Auto-path is just a shortcut to this:

 private string _property; public string MyProperty { get { return _property; } set { _property = value; } } 

So, if you omitted a hidden field in one of the methods (this is what the receivers and setters are actually), how should this method know how to store / receive the value?

+2
source share

You need to either provide the body for both the recipient and the setter, or not.

So, if you define one of them, this is no longer an auto property.

So you need to do:

Or

 public string MyProperty { get; set; }// Automatic property, no implementation 

OR

 public string MyProperty { get { return mMyProperty; } set { mMyProperty = value; PerformSomeAction(); } } 
+1
source share

If you are doing something in the setter, you will have to explicitly declare a variable. For example.

 private string _myProperty; public string MyProperty { get { return _myProperty; }; set { _myProperty = value; PerformSomeAction(); } } 

or - in the installer you can pass the value of the function and do what you want there ... provided that you want to change / check the value in the PerformSomeAction() function

0
source share

This is similar to the question of C # getter and setter shorthand .

When you manually specify the installer, it will not use the automatic property mechanism for the recipient, so the error message acts as if it were missing. You will need to write your own receiver when you specify the installer.

0
source share

All Articles