Queue.Peek throws an InvalidOperationException if the queue is empty

I have a simple queue for managing items added to my application.

From the current Microsoft documentation on their Queue.Peek Method :

screenshot

What is the point of using Peek () to view a queue if it still throws an invalid operation exception?

I thought the whole point of Peek () was to have code that did NOT throw exceptions.

+4
source share
2 answers

Even MSDN mentions the reason:

null . , Count catch InvalidOperationException, , .

, , , , , null. null ?

, , int. -1, ? , -1 , , .

Count, , :

var queue = new Queue<int>();
queue.Enqueue(-1);
while (queue.Count > 0)
{
    int current = queue.Peek();         // still in the queue
    Console.WriteLine(queue.Dequeue()); // now empty
}

, queue.Peek dataReader.Read. , Read bool, , . queue.Peek . , Peek, , .

, . , Enumerable.First, InvalidOperationException, .

+9

Peek - , . , , Peek Pop (Dequeue .NET). ( .NET, , Pop (/Dequeue), , .

, , Queue . , . , ( ) , Peek/Dequeue.

+3

All Articles