I have an object with a property for which I want to create a custom setter and also keep the automatic getter:
public class SomeObject { public int SomeProp { get; set; } public Nullable<short> MyProp { get { return MyProp; } set { if (value != null) { SomeProp = SomeWork(value); MyProp = value; } } } }
The problem is that I get a Stackoverflow error on the getter. How do I implement a property where I keep the getter as it is but only modify the setter?
The private getter/setter methods provide a place for adding extra behavior or error checking code. They can provide a place for logging state changes or access to the fields.
To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .
Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
You need to use a backing field for your property. You're getting a SO error because you're recursively referencing your MyProp
property in its own getter resulting in infinite recursion.
private short? _myProp; public short? MyProp { get { return _myProp; } set { if (value != null) { SomeProp = SomeWork(value); _myProp = value; } } }
NO, it's not possible. Either you make it a complete auto
property (OR) define both the getter
and setter
in which case you will have to provide the backing field since compiler won't create one for you.
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