Reputation: 1427
What is the best way to go about supporting an "auto" value for value types?
Let's say I wanted to float a texture 5 units off the right side of the screen. I wanted the end-developer to set the value like so:
mytexture.Margin.Right = 5;
mytexture.Margin.Left = int.Auto;
Internally, my 'layout manager' would need to know the end result of the positioning, but maintain that it is an automatic property for future comparisons and use.
So far I have been implementing this via a new value type that handles every possible conversion under the sun but has an extra field to declare whether or not it represents an automatically set value or not.
Is this correct? Or is there a better way of handling this? My code currently ends up as:
mytexture.Margin.Right = 5;
mytexture.Margin.Left = Size.Auto;
Upvotes: 2
Views: 267
Reputation: 26505
You can also model this after the GridLength type available in WPF.
They basically made a struct, with a double value (amongst other things). They added implicit cast operators so it is easy to use from code:
RowDefinition row = new RowDefinition();
row.Height = 25; //Same as new GridLength(25);
row.Height = GridLength.Auto;
I'm sure they specifically check for the static member, GridLength.Auto underneath the hood to do the work.
Upvotes: 1
Reputation: 1502806
It sounds very similar to Nullable<T>
, in terms of having "any value, but also a flag saying whether or not a value is set". You could either use Nullable<T>
directly, or if you felt that was a little bit of an abuse of the type, you could write your own similar type, e.g. Defaultable<T>
.
Upvotes: 1