Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
CharEnumerator.Dispose() Method in C#
The CharEnumerator.Dispose() method in C# is used to release all resources used by the current instance of the CharEnumerator class. This method implements the IDisposable interface and should be called when you're finished using the enumerator to ensure proper resource cleanup.
Syntax
Following is the syntax for the CharEnumerator.Dispose() method −
public void Dispose();
Parameters
This method does not take any parameters.
Return Value
This method does not return any value (void).
Using CharEnumerator.Dispose() Method
Example 1: Basic Usage
The following example demonstrates how to use the Dispose() method to clean up resources after enumerating through characters −
using System;
public class Demo {
public static void Main() {
string strNum = "356";
CharEnumerator ch = strNum.GetEnumerator();
while (ch.MoveNext())
Console.Write(ch.Current + " ");
Console.WriteLine();
// Dispose the enumerator to release resources
ch.Dispose();
Console.WriteLine("CharEnumerator disposed successfully.");
}
}
The output of the above code is −
3 5 6 CharEnumerator disposed successfully.
Example 2: Using 'using' Statement for Automatic Disposal
The recommended approach is to use the using statement, which automatically calls Dispose() when the scope ends −
using System;
public class Demo {
public static void Main() {
string text = "Hello";
using (CharEnumerator ch = text.GetEnumerator()) {
Console.Write("Characters: ");
while (ch.MoveNext()) {
Console.Write(ch.Current + " ");
}
Console.WriteLine();
} // Dispose() is automatically called here
Console.WriteLine("Resources automatically cleaned up.");
}
}
The output of the above code is −
Characters: H e l l o Resources automatically cleaned up.
Key Rules
-
Always call
Dispose()when finished with aCharEnumeratorto release resources. -
Use the
usingstatement for automatic disposal and exception safety. -
After calling
Dispose(), the enumerator should not be used again. -
It's safe to call
Dispose()multiple times on the same instance.
Conclusion
The CharEnumerator.Dispose() method is essential for proper resource management when working with character enumerators. Using the using statement is the preferred approach as it ensures automatic cleanup even if exceptions occur during enumeration.
