...in my post about Dynamic Attributes, I was specifically looking at the runtime modification of serialization attributes. This is not exactly appropriate. Attributes are there to add additional information to your assembly about a particular method, property, field, class, etc. The attributes are compiled into your assembly and available through reflection. This is very useful but not a good place to implement conditional functionality.
My solution was really not so complex. My need was to conditionally serialize a property of a class. Basically, under condition a, serialize PropertyA to xml and skip PropertyB. Under condition b, serialize PropertyB to xml and skip PropertyA.
One way to accomplish this would be to have to derivations of a common base class. FooA and FooB inherit from base class Foo. Each could use Attributes to mark the appropriate property [XmlIgnore]. So, in a sense, dynamic attributes, in an indirect sort of way.
The way I decided to accomplish this is pretty simple... The class has a public method called SerializeToXml. This method handles the serialization details for this class. Within this method, if a check for PropertyA finds it full of data, PropertyB is copied to a temporary local variable and then PropertyA is nullified. The class is serialized to file and then the value of the local temporary variable is returned to PropertyB. The result? PropertyB is not serialized because it is empty. Additionally, state is not disrupted because everything is restored following serialization.
Certainly, if someone implementing the Class were to serialize the class using System.Xml.Serialization, they would get both properties. I like this result because there may be a case where an application wants to save or transfer its state to some other application using the same class. Or maybe a different, third party application might need to consume the state data. It makes sense that should I deserialize and rehydrate this class, it would be pretty much the same instance. Of course, context comes into discussion, but not this one.
Remember Me
Theme design by Jelle Druyts
Pick a theme: BlogXP calmBlue Candid Blue dasBlog Discreet Blog Blue Elegante essence Just Html Mono Movable Radio Blue Movable Radio Heat orangeCream Portal Project84 Slate Sound Waves Tricoleur
Powered by: newtelligence dasBlog 1.8.5223.2
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Rusty Zarse
E-mail