I have a Rectangle property in my class, which I’d like to make accept Width and Height correctly, and also return them, as if I was dealing with a normal Rectangle.
Vector2 position;
Rectangle rectangle;
public Rectangle Rect
{
get { return rectangle; }
set { rectangle = value; position.X = value.X; position.Y = value.Y; }
}
Seems fine, works great. Except for when you want to get or set Width or X specifically.
How do I make that possible?
If the semantics of your class are such that you can be 100% certain that you’re never going to care when outsiders adjust
Rect, just expose it as a field and callers will be able to set its fields directly. If you cannot make that guarantee, then you might consider offering a method which passesrectangleto a callback method:That approach will avoid anyone having to make a copy of
rectanglejust to change one of its members. Probably not worth it with a 16-byte structure, but maybe worthwhile if a larger structure is necessary.A third approach would be to simply require your callers to do something like:
The final approach I’d suggest would be to follow the pattern of
Control.SetBounds, which includes an overload that takes theRectanglemembers as separate parameters, but takes an additional parameter which specifies which parameter or parameters should be copied to the appropriate members ofBounds.