Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter without body, Setter with

Tags:

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

like image 224
colmde Avatar asked May 23 '16 13:05

colmde


People also ask

What is a getter only property?

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.

What comes first getter or setter?

*I know there are no rules with these things, but practically every example ever, ever of properties defines the getter before the setter.

What is getter and setter in C#?

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.

What is property C#?

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.


2 Answers

You need to use a property with backing field:

private string mMyProperty; public string MyProperty {     get { return mMyProperty; }     set     {         mMyProperty = value;         PerformSomeAction();     } } 
like image 116
Marius Avatar answered Jan 23 '23 19:01

Marius


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?

like image 41
MakePeaceGreatAgain Avatar answered Jan 23 '23 19:01

MakePeaceGreatAgain