Edit in response to comments:
Sample: How can I know when the Width or Height is changed? Is that even possible?
No, this is not possible. However, it doesn't matter.
When you return a Size
from your class, since Size
is a struct
, you're returning a copy. Even if the user changes the Width
or Height
of the Size
you return, it has no impact on the mySize
struct in your class.
In order to change your Size, they need to change the entire thing, ie:
var temp = yourClass.MySize;
temp.Width = newWidth;
yourClass.MySize = temp; // The user will need to assign an entire Size
As far as you should be concerned, the Size
properties are effectively read only, since System.Drawing.Size
is a value type.
Original answer, given the assumption that Width and Height were properties of the user's class:
There are two main options -
You can compute the size on the fly, instead of storing it, based on your Width and Height:
public Size MySize
{
get {
return new Size(Width,Height);
}
set {
Width = value.Width;
Height = value.Height; // Set Width/Height appropriately
}
}
Another option is to recompute your size in your property setter for Width and Height:
public double Width
{
get { return width; }
set
{
width = value;
mySize = new Size(width, Height); // Compute new size, so it's always correct
}
}
Finally, if you're using something like INotifyPropertyChanged
to track changes, you could also subscribe to your own PropertyChanged
event, and if it's the appropriate property, recompute your size.