hi friends.! need little help. I couldn't find the way to check a stack is empty before pop up a element. when my program is running its give a error. please help me guys.. thank you in advance....

Do you have a code sample that is failing?

You can use the .Count property or (if you're using Linq) the .Any() method.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DW_404932_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         Stack<string> stk_str = new Stack<string>(20);
         string strData = "";

         if (stk_str.Any())
         {
            strData = stk_str.Pop();
         }

         stk_str.Push("asdf");
         
         if (stk_str.Any())
         {
            strData = stk_str.Pop();
         }

         Console.WriteLine(strData);
      }
   }
}

Edited 4 Years Ago by thines01: clarity

Comments
thank you from baby_C

Do you have a code sample that is failing?

You can use the .Count property or (if you're using Linq) the .Any() method.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DW_404932_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         Stack<string> stk_str = new Stack<string>(20);
         string strData = "";

         if (stk_str.Any())
         {
            strData = stk_str.Pop();
         }

         stk_str.Push("asdf");
         
         if (stk_str.Any())
         {
            strData = stk_str.Pop();
         }

         Console.WriteLine(strData);
      }
   }
}

ok.. I'll try it. thank you very much..!

This question has already been answered. Start a new discussion instead.