Stack.GetEnumerator Method in C# (original) (raw)

Last Updated : 04 Feb, 2019

This method returns an IEnumerator that iterates through the Stack. And it comes under the System.Collections namespace.Syntax:

public virtual System.Collections.IEnumerator GetEnumerator ();

Below programs illustrate the use of above-discussed method:Example 1:

csharp `

// C# program to illustrate the // Stack.GetEnumerator Method using System; using System.Collections;

class GFG {

// Driver code
public static void Main()
{

    // Creating a Stack
    Stack myStack = new Stack();

    // Inserting the elements into the Stack
    myStack.Push("Geeks");
    myStack.Push("Geeks Classes");
    myStack.Push("Noida");
    myStack.Push("Data Structures");
    myStack.Push("GeeksforGeeks");

    // To get an Enumerator
    // for the Stack
    IEnumerator enumerator = myStack.GetEnumerator();

    // If MoveNext passes the end of the
    // collection, the enumerator is positioned
    // after the last element in the Stack
    // and MoveNext returns false.
    while (enumerator.MoveNext()) {

        Console.WriteLine(enumerator.Current);
    }
}

}

`

Output:

GeeksforGeeks Data Structures Noida Geeks Classes Geeks

Example 2:

csharp `

// C# code to illustrate the // Stack.GetEnumerator Method using System; using System.Collections;

class GFG {

// Driver code
public static void Main()
{

    // Creating a Stack
    Stack myStack = new Stack();

    // Inserting the elements into the Stack
    myStack.Push(2);
    myStack.Push(3);
    myStack.Push(4);
    myStack.Push(5);
    myStack.Push(6);

    // To get an Enumerator
    // for the Stack
    IEnumerator enumerator = myStack.GetEnumerator();

    // If MoveNext passes the end of the
    // collection, the enumerator is positioned
    // after the last element in the Stack
    // and MoveNext returns false.
    while (enumerator.MoveNext()) {

        Console.WriteLine(enumerator.Current);
    }
}

}

`

Note:

Reference:

Similar Reads