I have a class named Myclass
with an override of ToString()
like this:
class Field
{
}
class MyClass
{
Field propretie1
Field propretie2
.
.
.
Field propretie15
public override string ToString()
{
StringBuilder temp = new StringBuilder();
temp.Append(propretie1.ToString())
temp.Append("|");
temp.Append(propretie2.ToString())
temp.Append("|");
.
.
temp.Append(propretie15.ToString())
return temp.ToString();
}
}
I'd like to know if there is a better way to get over all the properties of Myclass
with the declaration order to implement the ToString
function.
.Net offers an XmlSerializer object aimed at giving you a representation of your object. You can take advantage of that, just grabbing text nodes and joining them:
Calling ToString on properties which are complex classes is more complex... to do that use the XmlElement attribute on those properties so the serializer knows you want to output these properties, then allow implicit conversion to string so the serializer doesn't error. Weirdly you also need to implement implicit conversion from string too (I guess because the serializer has the ability to deserialize too); but that doesn't have to work. Very hacky.
An alternate is to make your child type serializable using the
[Serializable]
attribute, put[XmlIgnore]
on any public properties, then create a property with a get method calling to ToString function, and a dummy set method (again to trick the serializer). Not great, but it works.Working Example
Alternative
NB: