in a file I defined a public struct
public struct mystruct { public Double struct1; public Decimal struct2; }
In another I tried to do this:
class Test { mystruct my_va; public mystruct my_va { get { return my_va; } set { my_va = value; } } public Test() { my_va.struct1 = 10; } }
Intellisense recognizes My_va.struct1 but compiler says
Error 1 Cannot modify the return value of 'TEST.mystruct' because it is not a variable
How to correct the syntax ?
A struct can contain properties, auto-implemented properties, methods, etc., same as classes.
Claiming mutable structs are evil is like claiming mutable int s, bool s, and all other value types are evil. There are cases for mutability and for immutability. Those cases hinge on the role the data plays, not the type of memory allocation/sharing.
The only difference between these two methods is that the one allocates classes, and the other allocates structs. MeasureTestC allocates structs and runs in only 17 milliseconds which is 8.6 times faster than MeasureTestB which allocates classes! That's quite a difference!
Yup, it's absolutely right. You see, when you fetch My_va
, you're fetching a value - a copy of the current value of my_va
. Changing that value would have no benefit, because you'd be immediately discarding the copy. The compiler is stopping you from writing code which doesn't do what it looks like it does.
In general, avoid mutable structs. They're evil. In this case, you could (for example) change mystruct
to be immutable, but with a method like this:
public mystruct WithStruct1(double newValue) { return new mystruct(newValue, struct2); }
then change your constructor code to:
My_va = My_va.WithStruct1(10);
... although in this case it's far more likely (given that you're in a constructor) that you should be writing:
My_va = new mystruct(10, 0);
Not only should structs be immutable, they should be pretty rare in most codebases, IMO. Other than for Noda Time, I've hardly ever written my own custom values types.
Finally, please learn the .NET naming conventions and try to follow them, even for sample code :)
It is highly recommended to avoid mutable structs. They exhibit all sorts of surprising behaviour.
Solution: Make your struct immutable.
public struct MyStruct { public readonly double Value1; public readonly decimal Value2; public MyStruct(double value1, decimal value2) { this.Value1 = value1; this.Value2 = value2; } }
Usage:
class Test { private MyStruct myStruct; public Test() { myStruct = new MyStruct(10, 42); } public MyStruct MyStruct { get { return myStruct; } set { myStruct = value; } } }
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