There are many a situations you would have come across when you want to XML serialize an object but since the type is a non – serializable you can’t do it, and you could have done a lot of code for getting the functionality done. There is a much simpler and easy way to get this achieved.
Let me get you a scenario as below
public class HighlightInfo { public string Name { get; set; } public Color ForeColor { get; set; } }
As you all know System.Drawing.Color
is a structure and it is not xml serializable. So whenever you try to serialize “HighlightInfo”, you will get a null tag for "ForeColor"
. Below is how you achieve this functionality
public class HighlightInfo { public string Name { get; set; } [XmlIgnore] public Color ForeColor { get; set; } [XmlElement("ForeColor")] public string HtmlForeColor { get { return ColorTranslator.ToHtml(this.ForeColor); } set { this.ForeColor = ColorTranslator.FromHtml(value); } } }
Now this is a much easier way to achieve serialization without much trouble. However, this workaround might not work for few situations but it will obviously work for situations where you can transpose a data to another. E.g.) in our scenario we transposed color object to html color and vice versa.
Author:Jebarson | Follow him
Pingback: Tweets that mention Workaround For Non Serializable Types | Daily .Net Tips -- Topsy.com