0

Is there any circumstance that the red can be called given the green?

Unreachable code snippet

sammarcow
  • 2,736
  • 2
  • 28
  • 56

2 Answers2

4

That looks like unit test coverage, which should still reach the code since the method itself hasn't returned. However, if the automated testing you're using actually participates in the HTTP context, then it won't reach that other code if the response has ended.

You can prevent the response from ending by passing false to Redirect():

Response.Redirect(PageRedirect, false);

However, this is probably a bad idea. Consider the logical flow of what this code is doing. A redirect should end the response. You can choose not to end it if there's more server-side processing to be done, but this can often be pretty unintuitive. But if that server-side processing is another redirect, what is that even supposed to do? Redirect the user twice? Redirect once and ignore the second? Ignore the first and perform the second redirect? It's pretty unintuitive.

I'd recommend organizing the code such that the response terminates in the redirect. While it's not technically a return from the method, in this context it really should be logically treated like one.

David
  • 208,112
  • 36
  • 198
  • 279
  • If code below this snippet depends on "A" = true to execute without exception and "A" = false below it, will exception be thrown if I remove the red lines and change the green line to: Response.Redirect(PageRedirect, false); Context.ApplicationInstance.CompleteRequest(); – sammarcow Feb 03 '15 at 20:05
  • @sammarcow: It's not really clear what you're asking, perhaps you can update the question with a code sample illustrating the point? In any event, what I'm suggesting is that there shouldn't be additional code below the redirect. In the logical context of a web application, a redirect should be a terminating condition. – David Feb 03 '15 at 20:06
1

Never.

Most code analyzers will not figure out the code after HttpResponse.Redirect(url) is not executed - so compiler/analizers will complain about code in red possibly is wrong.

In reality it always throws ThreadAbort exception to avoid running more request handling code inadvertently - HttpResponse.Redirect.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179