[Mono-list] c# serialization

A Rafael D Teixeira rafaelteixeirabr@hotmail.com
Fri, 21 Feb 2003 00:17:43 -0300


>From: "Ricardo Kirkner" <mono@kirkner.com.ar>

>I would like to serialize a class that has the following structure (this is 
>an abstraction)
>
>public var1;
>public var2;
>public type;
>
>where one instance of this class can only have var1 or var2 instantiated. 
>Therefore I introduced variable type. So I can know which variable is 
>currently the right one (i.e. type=var1 or type=var2).
>When it comes to serialization, i would like to get only the "used" 
>variable serialized (i.e if type=var1 then I would like to have onle var1 
>serialized, and not both)

>So far i have found that in order to serialize a class i could prepend the 
>[Serializable] attribute to my class, and it would serialize every public 
>variable. In order not to get variable type serialized, i could prepend the 
>[XmlIgnore] attribute and that would do the job; but how can i tell that 
>one variable should get serialized based on the contents of another 
>variable of an instance of my class. I was thinking of something like...

>Ricardo Kirkner

First thing: The Serializable attribute is for Binary serialization, not for 
Xml serialization. These are two very different things...

I think you are probably heading for Xml serialization, so...

Second: If those var1 and var2 are reference types (classes instead of 
structs), just keep the unused one as null, and it won't be serialized to 
xml.

Third: If these are xml simple types (ints, floats, strings, ...), you can 
use a different approach: serializing them as attributes, that besides being 
more compact has a higher level of control using the xxxSpecified trick.

Example:

[XmlAttribute]
public int var1;

[XmlIgnore]
public bool var1Specified
{
  get { return type == "var1"; }
}

[XmlAttribute]
public string var2;

[XmlIgnore]
public bool var2Specified
{
  get { return type == "var2"; }
}

public string type;


Hope it helps,

Rafael Teixeira
Brazilian Polymath
Mono, MonoQLE Hacker


_________________________________________________________________
The new MSN 8: advanced junk mail protection and 2 months FREE* 
http://join.msn.com/?page=features/junkmail