C# | CharEnumerator.Dispose() Method
Last Updated :
30 Apr, 2019
This method is used to releases all resources used by the current instance of the CharEnumerator class. The Dispose() method leaves the CharEnumerator in an unusable state. So, this method should be called when a user finished their working with the CharEnumerator.
Syntax:
public void Dispose ();
Return Value: This method returns nothing.
Below are the programs to illustrate the use of CharEnumerator.Dispose() Method:
Example 1:
using System;
class GFG {
public static void Main()
{
string str = "GeeksforGeeks is Awesome!" ;
CharEnumerator chEnum = str.GetEnumerator();
while (chEnum.MoveNext())
Console.Write(chEnum.Current);
chEnum.Dispose();
try
{
Console.Write(chEnum.Current);
}
catch (Exception e)
{
Console.Write( "\nShows " + e.GetType() + " as" +
" the CharEnumerator object is disposed." );
}
}
}
|
Output:
GeeksforGeeks is Awesome!
Shows System.NullReferenceException as the CharEnumerator object is disposed.
Example 2:
using System;
class GFG {
public static void Main()
{
string str = "GeeksforGeeks is Awesome" ;
CharEnumerator chEnum = str.GetEnumerator();
while (chEnum.MoveNext())
{
Console.Write(chEnum.Current);
if (chEnum.Current == ' ' )
{
Console.WriteLine( ".\nDispose CharEnumerator object and " +
"try to print current character." );
chEnum.Dispose();
break ;
}
}
try
{
Console.Write(chEnum.Current);
}
catch (Exception e)
{
Console.Write( "Shows " + e.GetType() + " as the" +
" CharEnumerator object is disposed." );
}
}
}
|
Output:
GeeksforGeeks .
Dispose CharEnumerator object and try to print current character.
Shows System.NullReferenceException as the CharEnumerator object is disposed.
Reference:
Share your thoughts in the comments
Please Login to comment...