I have a property which is currently automatic.
public string MyProperty { get; set; }
However, I now 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 doesn't build... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial
I can't just have the getter return MyProperty
as it will cause an infinite loop.
Is there a way of doing this, or do I have to declare a private variable to refer to? I'd rather not as MyProperty
is used through out the code both in this class and outside it
The JavaScript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.
*I know there are no rules with these things, but practically every example ever, ever of properties defines the getter before the setter.
It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.
You need to use a property with backing field:
private string mMyProperty; public string MyProperty { get { return mMyProperty; } set { mMyProperty = value; PerformSomeAction(); } }
You can´t implement one without the other, as when using the one it refers to a (hidden) backing-field which is auto-generated in the case of an autogenerated property. However when you implement one you have to set this backing-field in both ways.
The auto-way is just a shortcut for this:
private string _property; public string MyProperty { get { return _property; } set { _property = value; } }
So if you´d omit the hidden field in one of the methods (this is what getters and setters are actually) how should this method know how to store/get the value?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With