text
stringlengths
0
13.4k
dequeueValue = queue.Dequeue(); // return Paul
dequeueValue = queue.Dequeue(); // return George
dequeueValue = queue.Dequeue(); // return Ringo
There is a non generic version of the type, which works with objects.
The namespace is:
using System.Collections;
Adn a code sample fo non generic queue:
Queue queue = new Queue();
queue.Enqueue("Hello World"); // string
queue.Enqueue(5); // int
queue.Enqueue(1d); // double
queue.Enqueue(true); // bool
queue.Enqueue(new Product()); // Product object
object dequeueValue;
dequeueValue = queue.Dequeue(); // return Hello World (string)
dequeueValue = queue.Dequeue(); // return 5 (int)
dequeueValue = queue.Dequeue(); // return 1d (double)
dequeueValue = queue.Dequeue(); // return true (bool)
dequeueValue = queue.Dequeue(); // return Product (Product type)
GoalKicker.com – .NET Framework Notes for Professionals
22
There is also a method called Peek() which returns the object at the beginning of the queue without removing it the
elements.
Queue<int> queue = new Queue<int>();
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
queue.Enqueue(40);
queue.Enqueue(50);
foreach (int element in queue)
{
Console.WriteLine(i);
}
The output (without removing):
10
20
30
40
50
GoalKicker.com – .NET Framework Notes for Professionals
23
Chapter 6: ReadOnlyCollections
Section 6.1: Creating a ReadOnlyCollection
Using the Constructor
A ReadOnlyCollection is created by passing an existing IList object into the constructor:
var groceryList = new List<string> { "Apple", "Banana" };
var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);
Using LINQ
Additionaly, LINQ provides an AsReadOnly() extension method for IList objects:
var readOnlyVersion = groceryList.AsReadOnly();
Note
Typically, you want to maintain the source collection privately and allow public access to the ReadOnlyCollection.
While you could create a ReadOnlyCollection from an in-line list, you would be unable to modify the collection
after you created it.
var readOnlyGroceryList = new List<string> {"Apple", "Banana"}.AsReadOnly();
// Great, but you will not be able to update the grocery list because
// you do not have a reference to the source list anymore!
If you find yourself doing this, you may want to consider using another data structure, such as an
ImmutableCollection.
Section 6.2: Updating a ReadOnlyCollection
A ReadOnlyCollection cannot be edited directly. Instead, the source collection is updated and the
ReadOnlyCollection will reflect these changes. This is the key feature of the ReadOnlyCollection.
var groceryList = new List<string> { "Apple", "Banana" };
var readOnlyGroceryList = new ReadOnlyCollection<string>(groceryList);