R – Setting DefaultValue for properties of non-Constant types


I have a Windows.Forms component which has a "mySize" property that returns a Size struct.
My intention was to have this property calculate the returned mySize automatically based on the size of the component, unless mySize has been explicity set, in which case, return the set value of mySize.
Unfortunately, now that I am embedding the component into a form, the Windows Forms designer has decided to start explicitly generating and setting a value for the mySize property, which is screwing me right up.

So I need to set a DefaultValue, so that the Designer will go away and leave me alone.

I've read up on answers dealing with System.ComponentModel.DefaultValue, so I know that I must manually set the value for the property in the constructor, but the answers and documentation I have found only deal with setting a DefaultValue of False, a Constant.

A Size struct is not a Constant and so the VB compiler is freaking out, telling me I can't set a Size as the DefaultValue for Property of Type Size because Sizes aren't constants.

This makes my brain hurt.

I can probably code around the problem by making getMySize and setMySize methods instead of using a property, but I'd like to know if there's actually any way to set the default property for a Size.

NB: I'm not using mySize as some kind of deranged attempt to override the Size property (which has a DefaultValue of 150×150, so SOMETHING seems to be able to set DefaultValues for Sizes); mySize is just some Size value required by the Class.

Best Solution

Instead of applying the DefaultValue attribute, write the following two methods:

bool ShouldSerializemySize() { ... }
void ResetmySize() { ... }

In ShouldSerializemySize, return true if the value should be serialized to code. In ResetmySize, reset the property to its default value.

The component designer will automatically pick up these methods via reflection.

More info here: http://msdn.microsoft.com/en-us/library/53b8022e(VS.71).aspx

Related Question