Access Denied – SharePoint code execution

When doing certain code operations in SharePoint like getting list of templates will lead to “Access Denied” exceptions. For such instances we can wrap the code within the following lines to execute code with elevated privileges.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
        //Code goes here
});

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

We were developing a Server Object Model based functionality in SharePoint involving site creation using template. During development we use to get the following error in quick watch window.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

To solve this issue we added the following code before the actual statement and issue was solved.

SPSecurity.CatchAccessDeniedException = false;