Click here to Skip to main content
13,454,296 members (58,322 online)
Click here to Skip to main content
Add your own
alternative version


8 bookmarked
Posted 11 Jul 2013

Helper for Serializing to a String

, 11 Jul 2013
Rate this:
Please Sign up or sign in to vote.
Helper for serializing objects to a string


I had a need to save a copy of a local variable to a class, but the Settings does not seem to support objects that are of a Type that is defined in the local project, so I could have created a special serializer, but decided that I wanted to create something that was more generic, and since wanted to save it in the Settings file, converting it to a string seemed like the best solution, and using XML would be a preferred format since it is easy to understand what is being saved. The next problem was that the XmlSerializer needs a Stream for conversion. With the complexity associate with handling the Stream, it seemed best to encapsulate the functionality using generics. Since there is no state required, it is preferable to implement these methods as static.

Potential Serializer Gotchas

There are a number of issues that you can run into when serializing, and the compiler does not seem to be much help and the error messages are not much either:

  • Classes serialized must be public
  • All properties that are marked to be serialized must have both a setter and getter.

The Code

The class that does the serialization and deserialization is two short static methods in a static class:

public static class Serializer
    private const string xmlnsString =
      "xmlns:xsi=\"" + 
      "XMLSchema-instance\" xmlns:xsd=\"\"";
    private const string headerString = "";
    /// <summary>
    /// Serialize an object to a string.
    /// </summary>
    public static string SerializedToString<t>(T serializableObject)
      if (serializableObject.Equals(default(T))) return string.Empty;
        var serializer = new XmlSerializer(typeof(T));
        using (var stringWriter = new StringWriter())
          serializer.Serialize(stringWriter, serializableObject);
          var str =  stringWriter.ToString();
          return str.Replace(xmlnsString, "{1}").Replace(headerString, "{0}")
              .Replace("\r\n", string.Empty);
      catch (Exception ex)
        return string.Empty;
    /// <summary>
    /// Deserialize an string into an object
    /// </summary>
    public static T DeSerializeFromString<t>(string serializedObject)
      if (string.IsNullOrWhiteSpace(serializedObject)) return default(T);
        var stringReader = new StringReader(string.Format(serializedObject,
              headerString, xmlnsString));
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
      catch (Exception exception)
        return default(T);

There is really no error handling, but it may be desirable to put it in. Also, the code removes some text that is extremely repetitive: the XML declaration line, and the declaration of the namespaces. The code is done so that if something besides what the code expects, there will be no harm, but some may think that the saved space is not worth it.


These methods makes it very easy to serialize an object to and from a string, but is not really appropriate for saving the serialization since it would the XMLSerializer supports a type of Stream, and can use a Stream to more directly support saving to file. There is also disadvantages of possible changes in the object that will not be supported unless there is some customization done on the objects for serialization, and XML is not an efficient way to save data.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Clifford Nelson
Software Developer (Senior) Clifford Nelson Consulting
United States United States
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
H. Mueller26-Jul-13 0:28
professionalH. Mueller26-Jul-13 0:28 
GeneralRe: My vote of 1 Pin
Clifford Nelson26-Jul-13 4:39
memberClifford Nelson26-Jul-13 4:39 
GeneralRe: My vote of 1 Pin
the.Kris29-Jul-13 6:24
memberthe.Kris29-Jul-13 6:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180321.1 | Last Updated 11 Jul 2013
Article Copyright 2013 by Clifford Nelson
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid