There’s a lot of information (including sample routines) on how to serialize/deserialize objects in C#.  Hunt down a couple of routines that accept generic types and add them to your personal utility class and reuse them forever.  Be aware, however, that there’s an issue with serializing nullable types. Basically it can’t be done if an object’s property is marked with an XmlAttribute.  You will need to mark the property as an XmlElement.

[XmlElement(IsNullable=true)] public DateTime? MachineDateChange { get ; set ; }

And use some caution as the property datatype must match the IsNullable setting for the XmlElement markup.  Believe it or not, the following “type mismatch” will throw an exception when serializing since MachineDateChange, in the following case, isn’t actually nullable like it is above:

[XmlElement(IsNullable = true)] public DateTime MachineDateChange { get; set; }

Here are a couple of good resources:

kick it on DotNetKicks.com

3 Responses to “C# Serializing Nullable Types”

  1. Thats great, however the XML serializer still emits the element with xsi:nil=”true”. Any idea how to supress it, if it is null.

    Thanks

  2. I wanna know too!!!

  3. @Lee @Matheus - So, the problem is with value types only since null reference types and strings are suppressed by default. The solution, in my opinion is totally obscure, but, believe it or not there’s a pattern to check if null and suppress as described here on StackOverflow: http://stackoverflow.com/quest.....serializer

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>