.NET API Documentation

System.Xml.XmlNodeReader.Dispose Method

Dispose Method

public void Dispose()

Summary

Releases all resources used by the current instance of the XmlNodeReader class.

Remarks

The Dispose method allows the XmlNodeReader object to release its resources. For objects that implement the IDisposable interface, calling this method is the recommended way to clean up managed and unmanaged resources.

The XmlNodeReader itself does not hold significant unmanaged resources, but it is good practice to call Dispose when you are finished with it to ensure proper cleanup.

This method does not throw an exception. If a method that depends on the XmlNodeReader throws an exception, the Dispose method can still be called to clean up resources.

You should call Dispose before you release your last reference to the XmlNodeReader. Otherwise, the system resources that the XmlNodeReader is holding onto might not be freed until the garbage collector calls the finalizer for the object. This can impact performance and consume resources.

In C# and Visual Basic, you can use the using statement to ensure that the Dispose method is called automatically when the scope of the object ends.

Example

The following example demonstrates how to use the using statement with XmlNodeReader.


using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        // Create an XmlDocument
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<root><child>Hello</child></root>");

        // Create an XmlNodeReader
        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);

        // Use the using statement to ensure Dispose is called
        using (reader)
        {
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.WriteLine($"Element: {reader.Name}");
                        break;
                    case XmlNodeType.Text:
                        Console.WriteLine($"Text: {reader.Value}");
                        break;
                }
            }
        } // reader.Dispose() is automatically called here
        Console.WriteLine("XmlNodeReader has been disposed.");
    }
}
            

Parameters

This method does not take any parameters.

Return Value

This method does not return a value.