Friday, 16 March 2012

Handling string null or empty in Deserialization c sharp

When we are deserializing the string to object which we are passing the parameter with dynamic values, we don't know the parameter is null or empty. If we do not handle null or empty then it will throws an exception. But if the method is generic type then we don't know which type of class it is to create an instance and return. To create an instance without new keyword and the type of class use the solution below.
public static T DeSerializeDataContract<T>(String obj)
        {
            if (string.IsNullOrEmpty(obj))
            {
                Type type = typeof(T);
                return (T)Activator.CreateInstance(type);
            }
            using (var stringReader = new StringReader(obj))
            using (var reader = new XmlTextReader(stringReader))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                return (T)serializer.ReadObject(reader);
            }

        }

No comments:

Post a Comment