954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

chech stack empty c#

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....

baby_c
Junior Poster
112 posts since May 2010
Reputation Points: 47
Solved Threads: 0
 

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);
      }
   }
}
thines01
Postaholic
Team Colleague
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
 

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..!

baby_c
Junior Poster
112 posts since May 2010
Reputation Points: 47
Solved Threads: 0
 

it worked..! thank you.. rep added..!

baby_c
Junior Poster
112 posts since May 2010
Reputation Points: 47
Solved Threads: 0
 

Thanks!

thines01
Postaholic
Team Colleague
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: