I started using classes that implement IDisposable to write blocks in threads using the using statement. This is useful to maintain proper nesting and to avoid missing or improperly placed start / end parts.
In principle, the constructor writes the beginning of the block (for example, opens the XML tag), Dispose () the end (for example, the closing XML tag). The following is an example of a UsableXmlElement (it is for large XML, so LINQ to XML or XmlDocument has no parameters in memory).
However, these IDisposable do not implement the complex template recommended by Microsoft, with Destructor / Finalizer, a separate Dispose (bool) method, and GC.SuppressFinalize (). Dispose just writes the final element and what it is.
Is there any downside to this, or is this a good way to maintain proper nesting of elements?
class UsableXmlElement : IDisposable { private XmlWriter _xwriter; public UsableXmlElement(string name, XmlWriter xmlWriter) { _xwriter = xmlWriter; _xwriter.WriteStartElement(name); } public void WriteAttribute<T>(string name, T value) { _xwriter.WriteStartAttribute(name); _xwriter.WriteValue(value); _xwriter.WriteEndAttribute(); } public void WriteValue<T>(T value) { _xwriter.WriteValue(value); } public void Dispose() { _xwriter.WriteEndElement(); } }
Usage looks like this:
var xWriter = new XmlWriter(...) using(var rootElement = new UsableXmlElement("RootElement", xWriter) { rootElement.WriteAttribute("DocVersion", 123) using(var innerElement = new UsableXmlElement("InnerElement", xwriter) {
Result:
<RootElement DocVersion="123"> <InnerElement> </InnerElement> </RootElement>
Erik hart
source share