Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom setter but auto getter [duplicate]

Tags:

c#

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?

like image 862
frenchie Avatar asked Aug 09 '16 18:08

frenchie


People also ask

What will happen if getters and setters are made private?

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.

How do you use setters and getters in two different classes?

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 .

What is an Auto Property C#?

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.

Why do we need getter and setter methods in Java?

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.


2 Answers

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;         }     } } 
like image 171
rory.ap Avatar answered Oct 08 '22 04:10

rory.ap


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.

like image 29
Rahul Avatar answered Oct 08 '22 04:10

Rahul