Problem with struct and property in c#

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 🙂

Leave a Comment

tech