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?
No, there is no syntax like this that will work. Setters are, well, setters, not a way to get something.
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); }
}
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