views:

167

answers:

2

I have a class where it's problematic to relay on the properties being serialized in alphabetical order at design time. In other words, property Z must be serialized before property A.

The problem arises because property property Z clears property A whenever it changes - which happens in InitializeComponent. I work around this problem by setting a FirstTime flag, but that seems messy.

I found a solution here (translated from Spanish), but that seems like over kill.

What's the correct way to handle the problem?

+1  A: 

I am the author of the "overkill" solution. :-) If you don't like the solution based on CodeDomSerializer, I thnik that your only option is to design your class so that properties can be initialized in any order (which is considered good practice anyway). Can you for example have property Z to not clear property A if it is the first time that its setter is invoked? Something like:

bool propertyZHasBeenSet=false;
SomeType propertyZ
{
    get {
        //Property getter
    }

    set {
        if(propertyZHasBeenSet) {
            //Clear property A
        } else {
            propertyZHasBeenSet=true;
        }
        //The remaining of the property setter
    }
}

I'm sure there must be a better way to accomplish the same thing, but you get the idea.

Konamiman
Hi, thanks for the reply. My solution at the moment is, like you said, based on not clearing the property if it's the first time the setter is invoked. I just like to be sure that I'm doing things the standard way. I have your solution book marked for when a little "overkill" is required ;-).
Jules
+2  A: 

The best practice here is to re-write your class so that all design-time properties are independent of each other. That is how all Microsoft-supplied designable types work.

I have almost fallen into this trap many times before, and I always solved it by making the funny inter-dependencies happen only at run time, not design time.

Christian Hayter
+1, and indeed this is how all *types* should work. Properties should *never* have this type of weird interaction and should *always* be settable in any order.
Greg Beech