views:

753

answers:

4

I have a class I've marked as Serializable, with a Uri property. How can I get the Uri to serialize/Deserialize without making the property of type string?

A: 

Uri class implements ISerializable Interface so it should be able to take care of serialization/deserialization.

TheVillageIdiot
Hmmm, maybe a 3.5 thing? I get an exception that there is no default constructor when I serialize in 2.0
Jeremy
That is for *binary* serialization; the question (see tags) is about *xml* serialization
Marc Gravell
A: 

Uri is already Serializeable, so I don't belive you have to do anything.

http://msdn.microsoft.com/en-us/library/system.uri(VS.80).aspx

Kobi
The tags suggest xmlserializer, so that (alone) doesn't do much
Marc Gravell
A: 

Implement and IDeserializationCallback and use that field on your own.

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ideserializationcallback.aspx

Timotei Dolean
The tags suggest xmlserializer - which doesn't support these
Marc Gravell
+10  A: 

With xml serializer, you are limited - it isn't as versatile as (say) some of the binaryformatter/ISerializable options. One frequent trick is to have a second property for serialization:

[XmlIgnore]
public Uri Uri {get;set;}

[XmlAttribute("uri")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public string UriString {
    get {return Uri == null ? null : Uri.ToString();}
    set {Uri = value == null ? null : new Uri(value);}
}

The two browsable attributes hide it from view (but it needs to be on the public API for XmlSerializer to use it). The XmlIgnore tells it not to try the Uri; and the [XmlAttribute(...)] (or [XmlElement(...)]) tells it to rename UriString when (de)serializing it.

(note that EditorBrowsable only applies to code outside the assembly declaring the type)

Marc Gravell