Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable value with xsd.exe generated class

I have been using xsd.exe to generate a class for deserializing XML into. I have decimal value in the source xsd that is not required:

<xs:attribute name="Balance" type="xs:decimal" use="optional" />

The resulting class from xsd generates the following code:

private decimal balanceField;

[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Balance {
    get {
        return this.balanceField;
    }
    set {
        this.balanceField = value;
    }
}

Which I note is not nullable.

How do I instead generate the field as nullable, illustrated as follows:

private decimal? balanceField;

[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal? Balance {
    get {
        return this.balanceField;
    }
    set {
        this.balanceField = value;
    }
}
like image 997
Don Vince Avatar asked Sep 14 '09 11:09

Don Vince


People also ask

What is XSD EXE?

The XML Schema Definition (Xsd.exe) tool generates XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.

How do you define a nullable class in C#?

A type is said to be nullable if it can be assigned a value or can be assigned null , which means the type has no value whatsoever. By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not. In C# and Visual Basic, you mark a value type as nullable by using the ?

What is nullable value in C#?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.


1 Answers

Currently it works as it should. I'm using xsd v2.0.50727.42 and:

<xs:element name="Port" type="xs:int" nillable="true" />

generates exactly what you've been looking for (without redundant ...Specified field and property):

private System.Nullable<int> portField;

[System.Xml.Serialization.XmlElementAttribute(IsNullable = true)]
public System.Nullable<int> Port {
    get {
        return this.portField;
    }
    set {
        this.portField = value;
    }
}
like image 121
Michał Powaga Avatar answered Oct 11 '22 00:10

Michał Powaga