6

I have a property

 [XmlElement]
 public string[] Emails { get; set; }

which is initialized as string[0] at constructor.

If I XML serialize and deserialize a default instance of this object, the property is NULL.

How can I tell the XML Serializer to use an empty array instead of NULL for this property?

3
  • 1
    You can always implement the {get; set;} so if null is ever set (or attempts to return null in the getter) it instead uses an empty array. EDIT: Just be sure if you do the check on the get to also store the empty array in the backing field rather than just returning a new instance. Commented Jul 15, 2013 at 14:44
  • @ChrisSinclair: I have hundred of such properties, is there a way without manual properties? Commented Jul 15, 2013 at 14:45
  • Not that I know of. You can create a separate utility class that will (likely via reflection) find all arrays (and collections?) that are null and set them to a new instance of their appropriate empty collection. Have it run through this utility when calling your central deserialization method. Commented Jul 15, 2013 at 14:54

1 Answer 1

8

5 years later... :) Replacing Array with List<> did the trick for me.

[XmlElement (IsNullable = false)]
public List<string> Emails {get;set;}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.