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.Clone() Method in C#
The CharEnumerator.Clone() method in C# is used to create a copy of the current CharEnumerator object. This method returns an object that must be cast to CharEnumerator to use its functionality. The cloned enumerator maintains the same position as the original enumerator at the time of cloning.
Syntax
public object Clone();
Return Value
Returns an object that is a copy of the current CharEnumerator instance. The returned object must be cast to CharEnumerator to access enumerator-specific methods.
Using CharEnumerator.Clone()
The following example demonstrates how to create and use a cloned CharEnumerator −
using System;
public class Demo {
public static void Main() {
string strNum = "356";
CharEnumerator ch = strNum.GetEnumerator();
while (ch.MoveNext()) {
Console.Write(ch.Current + " ");
CharEnumerator enumClone = (CharEnumerator)ch.Clone();
while (enumClone.MoveNext())
Console.Write(enumClone.Current + " ");
Console.WriteLine();
}
}
}
The output of the above code is −
3 5 6 5 6 6
Practical Example with Position Tracking
Here's another example that shows how the cloned enumerator preserves the current position −
using System;
public class CloneExample {
public static void Main() {
string text = "Hello";
CharEnumerator original = text.GetEnumerator();
// Move to position 2 (character 'l')
original.MoveNext(); // H
original.MoveNext(); // e
original.MoveNext(); // l
Console.WriteLine("Original current: " + original.Current);
// Clone at current position
CharEnumerator clone = (CharEnumerator)original.Clone();
Console.WriteLine("Clone current: " + clone.Current);
// Both continue from the same position
Console.Write("Original remaining: ");
while (original.MoveNext())
Console.Write(original.Current);
Console.Write("\nClone remaining: ");
while (clone.MoveNext())
Console.Write(clone.Current);
}
}
The output of the above code is −
Original current: l Clone current: l Original remaining: lo Clone remaining: lo
Key Points
The
Clone()method returns anobjectthat must be cast toCharEnumerator.The cloned enumerator starts at the same position as the original enumerator.
Both enumerators can be moved independently after cloning.
This method is useful when you need to iterate through the same string from the current position multiple times.
Conclusion
The CharEnumerator.Clone() method creates an independent copy of the current enumerator at its current position. This allows multiple iterations over the remaining characters without affecting the original enumerator's state, making it useful for scenarios requiring parallel enumeration.
