views:

28

answers:

2

For example I have class to serialize

[Serializable]
class Person
{
    [XmlAttribute("name")]
    string Name {get;set;}
}

I need to make Name attribute required. How to do this in .NET?

A: 

First of all, [Serializable] is not used by the XML Serializer.

Second, there is no way to make it required.

John Saunders
A: 

I believe you are confusing XML with an XSD. If you want your property to always have a value, initialize this property in the constructor, and throw an exception if anyone tries to set it to empty or null.

class Person
{

  private string _Name = "Not Initialized";
  [XmlAttribute("name")]
  string Name {
    get { return _Name;}
    set {
        if(value == null || value==string.Empty) throw new ArgumentException(...);

        _Name = value;
    }
   }
}
MrGumbe
-1: The person class is not XML-serializable because it has no public parameterless constructor. Fix that and I'll remove the downvote.
John Saunders
This will not work. Such constructor will never used with serialization, so the Name setter will not called too.
darja