This topic has not yet been rated - Rate this topic

CharEnumerator Class

Supports iterating over a String object and reading its individual characters. This class cannot be inherited.

System.Object
  System.CharEnumerator

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class CharEnumerator : ICloneable, 
	IEnumerator<char>, IEnumerator, IDisposable

The CharEnumerator type exposes the following members.

  Name Description
Public property Supported by the XNA Framework Current Gets the currently referenced character in the string enumerated by this CharEnumerator object.
Top
  Name Description
Public method Supported by the XNA Framework Clone Creates a copy of the current CharEnumerator object.
Public method Dispose Releases all resources used by the current instance of the CharEnumerator class.
Public method Supported by the XNA Framework Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Supported by the XNA Framework GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by the XNA Framework MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework MoveNext Increments the internal index of the current CharEnumerator object to the next character of the enumerated string.
Public method Supported by the XNA Framework Reset Initializes the index to a position logically before the first character of the enumerated string.
Public method Supported by the XNA Framework ToString Returns a string that represents the current object. (Inherited from Object.)
Top
  Name Description
Explicit interface implemetation Private method Supported by the XNA Framework IDisposable.Dispose Releases all resources used by the CharEnumerator class.
Explicit interface implemetation Private property Supported by the XNA Framework IEnumerator.Current Infrastructure. Gets the currently referenced character in the string enumerated by this CharEnumerator object. For a description of this member, see IEnumerator.Current.
Top

A CharEnumerator provides read-only access to the characters in a referenced String object. For example, the foreach statement of the Microsoft Visual Basic and C# programming languages, which iterates through the elements of a collection, retrieves a CharEnumerator from a String object in order to iterate through the characters in that object.

There is no public constructor for CharEnumerator. Instead, call a String object's GetEnumerator method to obtain a CharEnumerator that is initialized to reference the string.

A CharEnumerator maintains an internal index to the characters in the string the CharEnumerator references. The state of the index is invalid when it references a character position logically before the first character or after the last character in the string, and valid when it references a character within the string. The index is initialized to a position logically before the first character, and is set to a position after the last character when the iteration is complete. An exception is thrown if you attempt to access a character while the index is invalid.

The MoveNext method increments the index by one, so the first and subsequent characters are accessed in turn. The Reset method sets the index to a position logically before the first character. The Current property retrieves the character currently referenced by index. The Clone method creates a copy of the CharEnumerator.

Note Note

Several independent instances of CharEnumerator across one or more threads can have access to a single instance of String. This class is implemented to support the IEnumerator interface. For more information regarding the use of an enumerator, see the IEnumerator topic.

The following example uses the CharEnumerator class to enumerate the individual characters in a string. It instantiates a CharEnumerator object by calling the String.GetEnumerator method, moves from one character to the next by calling the MoveNext method, and displays the current character by retrieving the value of the Current property.


string title = "A Tale of Two Cities";
CharEnumerator chEnum = title.GetEnumerator();
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null; 

while (chEnum.MoveNext())
{
   outputLine1 += ctr < 10 || ctr % 10 != 0 ? "  " : (ctr / 10) + " ";
   outputLine2 += (ctr % 10) + " ";
   outputLine3 += chEnum.Current + " ";
   ctr++;
}

Console.WriteLine("The length of the string is {0} characters:", 
                  title.Length);
Console.WriteLine(outputLine1);
Console.WriteLine(outputLine2);    
Console.WriteLine(outputLine3);
// The example displays the following output to the console:      
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s


Note, however, that the same operation can be performed somewhat more intuitively by using foreach (in C#) or For Each (in Visual Basic), as the following example shows.


string title = "A Tale of Two Cities";
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null; 

foreach (char ch in title)
{
   outputLine1 += ctr < 10 || ctr % 10 != 0 ? "  " : (ctr / 10) + " ";
   outputLine2 += (ctr % 10) + " ";
   outputLine3 += ch + " ";
   ctr++;
}

Console.WriteLine("The length of the string is {0} characters:", 
                  title.Length);
Console.WriteLine(outputLine1);
Console.WriteLine(outputLine2);    
Console.WriteLine(outputLine3);
// The example displays the following output to the console:      
//       The length of the string is 20 characters:
//                         1                   2
//       1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
//       A   T a l e   o f   T w o   C i t i e s


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Explicit Interface IDisposable

Consulting source code, Object IEnumerator.Current  is the ONLY member with explicit interface implementation. Other members of respective interfaces are implicit implementation.

Explicit Interface Implementation (C# Programming Guide)

- http://msdn.microsoft.com/en-us/library/ms173157.aspx

Implicit and Explicit Interface Implementations

- http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx

Design Guideline Update: Explicit Member Implementation

- http://blogs.msdn.com/b/brada/archive/2003/11/15/50721.aspx

// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
/*============================================================
**
** Class: CharEnumerator
**
**
** Purpose: Enumerates the characters on a string.  skips range
**          checks.
**
**
============================================================*/
namespace System {

    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;

[System.Runtime.InteropServices.ComVisible(true)]
    [Serializable]
    public sealed class CharEnumerator : IEnumerator, ICloneable, IEnumerator<char>, IDisposable {
        private String str;
        private int index;
        private char currentElement;

        internal CharEnumerator(String str) {
            Contract.Requires(str != null);
            this.str = str;
            this.index = -1;
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public Object Clone() {
            return MemberwiseClone();
        }

        public bool MoveNext() {
            if (index < (str.Length-1)) {
                index++;
                currentElement = str[index];
                return true;
            }
            else
                index = str.Length;
            return false;

        }

        public void Dispose() {
            if (str != null)
                index = str.Length;
            str = null;
        }

        /// <internalonly/>
        Object IEnumerator.Current {
            get {
                if (index == -1)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
                if (index >= str.Length)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));

                return currentElement;
            }
        }

        public char Current {
            get {
                if (index == -1)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
                if (index >= str.Length)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
                return currentElement;
            }
        }

        public void Reset() {
            currentElement = (char)0;
            index = -1;
        }
    }
}

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==
/*============================================================
**
** Class: CharEnumerator
**
**
** Purpose: Enumerates the characters on a string.  skips range
**          checks.
**
**
============================================================*/
namespace System {

    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;

[System.Runtime.InteropServices.ComVisible(true)]
    [Serializable]
    public sealed class CharEnumerator : IEnumerator, ICloneable, IEnumerator<char>, IDisposable {
        private String str;
        private int index;
        private char currentElement;

        internal CharEnumerator(String str) {
            Contract.Requires(str != null);
            this.str = str;
            this.index = -1;
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public Object Clone() {
            return MemberwiseClone();
        }

        public bool MoveNext() {
            if (index < (str.Length-1)) {
                index++;
                currentElement = str[index];
                return true;
            }
            else
                index = str.Length;
            return false;

        }

        public void Dispose() {
            if (str != null)
                index = str.Length;
            str = null;
        }

        /// <internalonly/>
        Object IEnumerator.Current {
            get {
                if (index == -1)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
                if (index >= str.Length)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));

                return currentElement;
            }
        }

        public char Current {
            get {
                if (index == -1)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
                if (index >= str.Length)
                    throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
                return currentElement;
            }
        }

        public void Reset() {
            currentElement = (char)0;
            index = -1;
        }
    }
}

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.