I’d like to know whether the following is possible with C# properties.
I have a class “Transform” that holds a 4×4 matrix in a private member field. Now I want to create a property like this:
Matrix m;
public Vector3 Position
{
get { return new Vector3(m[12], m[13], m[14]); }
set { m[12] = value.X; m[13] = value.Y; m[14] = value.Z; }
}
but i’d like to provide the following functionality:
Transform myTransform = new Transform();
myTransform.Position.X += 3.0f;
such that the Property directly can be changed as if it was a variable. is this somehow possible with C#? (Vector3 and Matrix both are structs.)
thanks!
No, this won’t work. Think about it – your getters and setters are really doing something. You can’t bypass them without changing the semantics completely, and I wouldn’t expect a setter to run just because I changed something in what the getter had returned.
Do you really have to have mutable structs to start with? You’ll find all kinds of corner cases and weirdnesses. Why not make them immutable, and write:
or
That would save you having to build the
Vector3in the first place.Mutable structs are very, very rarely the right solution. In a very few cases they may be reasonable for performance reasons, but I’d explore all other options first.