I know stack is best and easiest way, yet could it be possible to obtain the last element in a queue without having to dequeue anything?
If you really need to you can use this but consider using a different data structure:
public static class QueueExtensions
{
const BindingFlags _flags =
BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance;
private static readonly FieldInfo _array =
typeof(Queue).GetField("_array", _flags);
private static readonly FieldInfo _size =
typeof(Queue).GetField("_size", _flags);
public T LastItem(this Queue value)
{
if (value == null)
throw new ArgumentNullException("value");
if (value.Count == 0)
throw new ArgumentException("The queue cannot be empty.", "value");
var array = (T[])_array.GetValue(value);
var size = (int)_size.GetValue(value);
return array[size - 1];
}
}