Stack.Clear Method

Definition

Removes all objects from the Stack.

C#
public virtual void Clear();

Examples

The following example shows how to clear the values of the Stack.

C#
using System;
using System.Collections;

public class SamplesStack  {

   public static void Main()  {

      // Creates and initializes a new Stack.
      Stack myStack = new Stack();
      myStack.Push( "The" );
      myStack.Push( "quick" );
      myStack.Push( "brown" );
      myStack.Push( "fox" );
      myStack.Push( "jumps" );

      // Displays the count and values of the Stack.
      Console.WriteLine( "Initially," );
      Console.WriteLine( "   Count    : {0}", myStack.Count );
      Console.Write( "   Values:" );
      PrintValues( myStack );

      // Clears the Stack.
      myStack.Clear();

      // Displays the count and values of the Stack.
      Console.WriteLine( "After Clear," );
      Console.WriteLine( "   Count    : {0}", myStack.Count );
      Console.Write( "   Values:" );
      PrintValues( myStack );
   }

   public static void PrintValues( IEnumerable myCollection )  {
      foreach ( Object obj in myCollection )
         Console.Write( "    {0}", obj );
      Console.WriteLine();
   }
}


/*
This code produces the following output.

Initially,
   Count    : 5
   Values:    jumps    fox    brown    quick    The
After Clear,
   Count    : 0
   Values:
*/

Remarks

Count is set to zero, and references to other objects from elements of the collection are also released.

This method is an O(n) operation, where n is Count.

Applies to

Toode Versioonid
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0