Last active
December 5, 2015 23:12
-
-
Save jennings/46c20733df559d02b9ad to your computer and use it in GitHub Desktop.
A sample program for Stack Overflow question 34111695 (http://stackoverflow.com/q/34111695/19818)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See: http://stackoverflow.com/q/34111695/19818 | |
namespace StackOverflow34111695 | |
{ | |
using System; | |
using System.IO; | |
using System.Xml; | |
using System.Xml.Schema; | |
using System.Xml.Serialization; | |
public struct Maybe<T> : IXmlSerializable where T : class | |
{ | |
public readonly T _value; | |
public Maybe(T value) | |
{ | |
_value = value; | |
} | |
public override string ToString() | |
{ | |
if (_value == null) | |
{ | |
return "None"; | |
} | |
return string.Format("Some({0})", _value); | |
} | |
XmlSchema IXmlSerializable.GetSchema() { return null; } | |
void IXmlSerializable.ReadXml(XmlReader reader) | |
{ | |
var value = (T)reader.ReadElementContentAs(typeof(T), null); | |
var maybe = new Maybe<T>(value); | |
this = maybe; | |
} | |
void IXmlSerializable.WriteXml(XmlWriter writer) | |
{ | |
if (_value == null) | |
{ | |
// I want to emit nothing | |
} | |
else | |
{ | |
writer.WriteValue(_value); | |
} | |
} | |
} | |
[XmlRoot("SomeObject")] | |
public class SomeObjectV1 | |
{ | |
public string MaybeAString { get; set; } | |
} | |
[XmlRoot("SomeObject")] | |
public class SomeObjectV2 | |
{ | |
public Maybe<string> MaybeAString { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var obj = new SomeObjectV2 { MaybeAString = new Maybe<string>(null) }; | |
Console.WriteLine("ORIGINAL PROPERTY VALUE: <{0}>", obj.MaybeAString); | |
Console.WriteLine(); | |
// V2 of the app serializes a value | |
var serializerV2 = new XmlSerializer(typeof(SomeObjectV2)); | |
var writer = new StringWriter(); | |
serializerV2.Serialize(writer, obj); | |
var serialized = writer.ToString(); | |
Console.WriteLine("SERIALIZED VALUE:"); | |
Console.WriteLine(serialized); | |
Console.WriteLine(); | |
// V1 of the app deserializes the value | |
var serializerV1 = new XmlSerializer(typeof(SomeObjectV1)); | |
var reader = new StringReader(serialized); | |
var deserialized = (SomeObjectV1)serializerV1.Deserialize(reader); | |
Console.WriteLine("DESERIALIZED PROPERTY: <{0}>", deserialized.MaybeAString); | |
Console.WriteLine(deserialized.MaybeAString == null ? "Yay! It worked!" : "It's an empty string, not null :("); | |
Console.WriteLine(); | |
Console.WriteLine("Press any key to exit."); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment