Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from setter

I have an immutable struct and would like to keep it immutable, but also allow schematics like var p2 = p1.v = 3. I thought that the following might work, but it appears not:

public struct Number {
    readonly int n;

    public int N {
        get{ return n; }
        set{ return new Number(value); }
    }

    public Number(int newN) {
        n = newN;
    }
}

Is there any way to get var p2 = p1.v = 3 or var p2 = (p1.v = 3) to work?

like image 464
user60561 Avatar asked May 24 '26 17:05

user60561


2 Answers

No, there is no syntax like this that will work. Setters are, well, setters, not a way to get something.

like image 97
Jesse C. Slicer Avatar answered May 26 '26 06:05

Jesse C. Slicer


First of all you want to do something that no one will be able to read. If you structure is immutable what one should expect as result of p1.v = 3? Obviously p1 should not change, no one expect setter to return value... the only reasonable behavior would be to see an exception "This object is immutable", but than lack of setter would be much better indication of the property being read only....

Possibly you trying to implement something like fluent interface which is much more common:

 var newValue = oldValue.WithOneProperty(5).WithOtherProperty(3);

 class Number 
 {
   int oneProperty;
   int otherProperty;
   Number WithOneProperty(int v) { return new Number(v, this.otherProperty); }     
   Number WithOtherProperty(int v) { return new Number(this.oneProperty, v); }
 }
like image 33
Alexei Levenkov Avatar answered May 26 '26 07:05

Alexei Levenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!