All About Assert Part IV: When Assert Won't Help

In Assert Myth #7, I mention three ways for a demand for a permission to fail even though that permission was asserted.  The first three are:

In addition, I mentioned that there were at least two other ways that this situation could occur.  Nicole managed to figure both of them out before I posted them ... here they are:

  • Permission demands that don't do a stack walk

If you think about this, it makes a lot of sense.  Assert works by stopping the stack walk before it reaches a frame that doesn't have the required permissions.  If you're using LinkDemand or Inheritance demand, which don't perform full stack walks, then they won't hit the assert, and there will be an exception.  (Of course for this exception to occur, an assembly that the code that is doing the Assert is calling into would have to be untrusted, and the exception would fire anyway).

  • Other stack walk modifiers further on in the call stack

The easiest example of this occurs if I Assert FileIO, and then a method that I call Denys FileIO, an eventual stack walk will hit the Deny before the Assert, and cause an exception at that point.

 ... and that about wraps up my discussion of Asserts.  To recap:

  1. What Assert Actually Does
  2. What Assert Is Good For
  3. Dispelling the Myths
  4. When Assert Won't Help