Is there any way to serialize a property with an internal setter in C#?
I understand that this might be problematic – but if there is a way – I would like to know.
Example:
[Serializable] public class Person { public int ID { get; internal set; } public string Name { get; set; } public int Age { get; set; } }
Code that serializes an instance of the class Person:
Person person = new Person(); person.Age = 27; person.Name = 'Patrik'; person.ID = 1; XmlSerializer serializer = new XmlSerializer(typeof(Person)); TextWriter writer = new StreamWriter(@'c:\test.xml'); serializer.Serialize(writer, person); writer.Close();
Result (missing the ID property):
<?xml version='1.0' encoding='utf-8'?> <Person xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <Name>Patrik</Name> <Age>27</Age> </Person>
If it is an option,
DataContractSerializer(.NET 3.0) can serialize non-public properties:With the xml (re-formatted):