views:

189

answers:

2

Hi,
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 150x150, so SOMETHING seems to be able to set DefaultValues for Sizes); mySize is just some Size value required by the Class.

+2  A: 

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

Joe Albahari
As an aside: XmlSerializer will also use ShouldSerialize*, but only if it is public.
Marc Gravell
A: 

I've noticed that there's actually an specific example given for setting a defaultValue of type Size in the Community Content section of DefaultValue's MSDN page, which suggests using the DefaultValue constructor described on this page.

Unfortunately, while the example given there is correct, in that it works, it seems to me that the MSDN documentation would not naturally lead anyone to this answer.

I'm going to set albahari's answer as the answer to this question (because his answer at least makes some kind of sense) and leave this example here for completeness' sake.

Frosty840