Jai
Jai

Reputation: 8363

C#: Debug.Assert() with complex condition

I'm writing a library where internally it uses a ConcurrentQueue. In one of the private method, I want to make sure that the item that I currently have is the item that will be dequeued (i.e. if I did not write my codes wrongly, this should be the expected behavior). How do I assert this correctly?

My current attempt is:

#if DEBUG
    object peeked = null;
    queue.TryPeek(out peeked);
    Debug.Assert(peeked == itemThatWillBeDequeued);
#endif

Which looks rather weird to me - if I need to use #if directive, then I wouldn't have used Debug.Assert(). However, there is no way I could directly place that ConcurrentQueue.TryPeek() into the assert statement inlinely either. Furthermore, doing that inline would probably mean that ConcurrentQueue.TryPeek() would run in release at runtime (unless I'm mistaken).

What should be the correct way to do this?

Upvotes: 3

Views: 161

Answers (2)

Klaus Gütter
Klaus Gütter

Reputation: 11997

If you want to avoid the extra method suggested by Bacon, you could use a LINQ expression:

Debug.Assert(((Func<object>)(() => {
    object peeked;
    return queue.TryPeek(out peeked) ? peeked : null;
}))() == itemThatWillBeDequeued);

Explanation: ((Func<object>)(() => { ... })) will create a function object from the enclosed code. The () will execute this function and return its result.

Upvotes: 3

Bacon
Bacon

Reputation: 483

you can wrap the call in a method

Debug.Assert(itemThatWillBeDequeued.equals(PeekQueue(queue)));

...

static object PeekQueue(ConcurrentQueue queue)
{
  object peeked = null;
  queue.TryPeek(out peeked);
  return peeked;
}

Upvotes: 2

Related Questions