I have a class which is used for Xml Serialization.
Inside which I have a nullable property which is decorated with XmlAttribute:
[XmlAttribute(\"la
I know this topic is old. This is the solution I came with. A class which encapsulates the type, and has implicit casting to the type. When serializing, the member variable can be marked with IsNullable = false without getting compiler errors, and blocking it from being serialized when null.
public class Optional where T : struct, IComparable
{
public Optional(T valueObject)
{
Value = valueObject;
}
public Optional()
{
}
[XmlText]
public T Value { get; set; }
public static implicit operator T(Optional objectToCast)
{
return objectToCast.Value;
}
public static implicit operator Optional(T objectToCast)
{
return new Optional(objectToCast);
}
}
Then use it in your class
[Serializable]
[XmlRoot(ElementName = "foo")]
public class foo
{
[XmlElement(ElementName = "myInteger", isNullable = false)]
Optional myInt;
}
You can do things like
myFoo.myInt = 7;
int j = 8 + myFoo.myInt;
For all purposes it's an int. For serialization purposes, it can be null and blocked from being serialized.