GetEnumerator method in VB .Net

String.GetEnumerator() method used to retrieve individual character from the string through each iteration. It gives better performance as compare to foreach loop and it is faster than foreach loop. Enumerator use to keep thing easy.
  • 7044
 

String.GetEnumerator() method used to retrieve individual character from the string through each iteration. It gives better performance as compare to foreach loop and it is faster than foreach loop. Enumerator use to keep thing easy. GetEnumerator method defined by IEnumerable interface, it returns an IEnumerator interface.

string-inumerator1.gif
Those collections implemented by IEnumerable that can be used with a foreach statement. Many of them have confusion in IEnumerator and IEnumerable. IEnumerator do its iteration over a non-generic collection and CharEnumerator implements both the non-generic IEnumerable and the generic IEnumerable<char> interfaces. To use string.GetEnumerator method you should add System.Collections.Generic namespace in your program.

Code

Module
Module1
    Sub Main()
        Dim Str1 As String = "Welcome to "
        Dim Enumerator As CharEnumerator = Str1.GetEnumerator()

        While Enumerator.MoveNext()
            Console.Write("{0}", Enumerator.Current)
        End While

        EnumerateAndDisplay("VB .Net Heaven")
        Console.ReadLine()
    End Sub

    Function EnumerateAndDisplay(str2 As [String]) As String
        Dim OperandEnum As IEnumerator = str2.GetEnumerator()
        While OperandEnum.MoveNext()
            Console.Write("{0}", OperandEnum.Current)
        End While
        Return str2
    End Function
End Module

Output

string-inumerator.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.