System.Uri implements ISerializable, but gives error?

.net, xml-serialization

Solution

In order to be serialized to XML, `Uri` class should have a parameterless constructor, which it doesn't: `Uri` is designed to be immutable. Honestly, I can't see why it cannot be serialized without having a parameterless constructor.

To circumvent this, either change `URI` property type to `string`, or add one more property called `_URI`, mark `URI` with `XmlIgnoreAttribute` and rewrite it's `get` method as `get { return new Uri(_URI); }`.

Problem

Possible Duplicate: How to (xml) serialize a uri To my knowledge `Uri` implements ISerializable, but throws error when used like this: ``` XmlSerializer xs = new XmlSerializer(typeof(Server)); xs.Serialize(Console.Out, new Server { Name = "test", URI = new Uri("http://localhost/") }); public class Server { public string Name { get; set; } public Uri URI { get; set; } } ``` Works just fine if `Uri` type is changed to `string`. Anyone knows what is the culprit? Solution proposed by Anton Gogolev: ``` public class Server { public string Name { get; set; } [XmlIgnore()] public Uri Uri; [XmlElement("URI")] public string _URI // Unfortunately this has to be public to be xml serialized. { get { return Uri.ToString(); } set { Uri = new Uri(value); } } } ``` (Thanks for SLaks also pointing out the backwardness of my method...) This produces XML output: ``` <Server> <URI>http://localhost/</URI> <Name>test</Name> </Server> ``` I rewrote it here so the code is visible.

Original source

Related problems