Jan 27 2011

Workaround For Non Serializable Types

Category: .netJebarson Jebamony @ 5:37 am

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.

One Response to “Workaround For Non Serializable Types”

  1. Microsoft Programmers » Guide: Write Your Own Syntax Highlighter says:

    [...] the issue that the Color is not serializable (For more info on the same do read the post “Workaround For Non Serializable Types“). The “Words” will be a comma seperated words to be highlighted. The list of [...]

Leave a Reply