segunda-feira, 27 de maio de 2013

XML Serialization with Generics

Hello,

After a long pause writing posts, I'm back to speak about one very nice feature that .Net brought to us: Generics. I'm writing about Generics now, because in this post I will implement a XML Serialization Helper class, that will be very useful to finalize my previous post about Send Email.

This will be a short post, as there are a extension information about Generics on internet. For example: An Introduction to C# Generics - 2005.

Generics provide the following benefits:
  • Code Reuse
  • Type Check on compile time
  • Performance
if we want to write some XML Serialization Helper class, this can be the API one solution:
public interface IXMLSerializationHelper
{
        string SerializeToString(Newsletter objToSerialize);
        Newsletter DeserializeToString(string objToDeserialize);
}

Problem: The problem of this solution is that, Newsletter are hard-code. If we need to serialize Product Class tomorrow, we will have to write a new API.

Solution 2:
public interface IXMLSerializationHelper
{
        string SerializeToString(Object objToSerialize);
        Object DeserializeToString(string objToDeserialize);
}

Problem: This is a improvement against solution 1, but still not the best solution as this will require boxing that will affect the performance. For more have a look here

Solution 3 using Generics:
public interface IXmlSerializationHelper<T>
    {
        string SerializeToString(T objToSerialize);
        T DeserializeToString(string objToDeserialize);
    }

public class XmlSerializationHelper<T> : IXmlSerializationHelper<T>
    {
        /// <summary>
        /// Serializing to String
        /// </summary>      
        public string SerializeToString(T objToSerialize)
        {
            var sb = new StringBuilder();
            var serializer = new XmlSerializer(typeof(T));
            using (var writer = new StringWriter(sb))
            {              
                serializer.Serialize(writer, objToSerialize);
            }

            return sb.ToString();
        }


        /// <summary>
        /// deserializing to T type
        /// </summary>
        public T DeserializeToString(string data)
        {
            var serializer = new XmlSerializer(typeof(T));
            T result;
            using (var reader = new StringReader(data))
            {
                result = (T) serializer.Deserialize(reader);
            }
            return result;
        }
    }

This solution take advantage of Generics. Examples:

var model = GetNewsletterModel();
var serializer = new XmlSerializationHelper<NewsletterModel>();
serializer.SerializeToString(model);

Or

var model = GetProductsModel();
var serializer = new XmlSerializationHelper<ProductsModel>();
serializer.SerializeToString(model);

This is all for now. I hope come back soon.