Workaround For Non Serializable Types

By | February 24, 2011

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

Author: Jebarson

Jebarson is a consultant at Microsoft. In his overall experience of 7+ years, his expertise ranges from VB6, COM / DCOM, .net, ASP.net, WPF, WCF, SL, SQL. He has a greater love for OOA / OOD and SOA. His current focus is on Azure, Windows Phone 7, Crm and much more. He is also a frequent speaker of different community events. He blogs at http://www.jebarson.info/ . You can follow him at @Jebarson007 . Jebarson having good set of tutorials written on Windows Azure, you can found them http://bit.ly/houBNx . He is a contributor of this site and shared many tips and tricks.

One thought on “Workaround For Non Serializable Types

  1. Pingback: Tweets that mention Workaround For Non Serializable Types | Daily .Net Tips -- Topsy.com

Comments are closed.