How to let try-catch works in LINQPad
I'm trying to try-catch the folowing code in LINQPad. But LINQPad always stopped on Line 3. Can I just leave try-catch works as expected?
try { headers.GetValues("User-Agent"); } catch (IndexOutOfRangeException) { headers.Remove("User-Agent"); headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)"); }
Comments
headers.AllKeys.Contains("User-Agent")
to check for an existing value.But, a shorter path is redefining the header. Assuming Headers is of type WebHeaderCollection, use the this[string] or this[HttpRequestHeader] property (which you can examine using built-in ILSpy).
Using both named header "User-Agent" and enum HttpRequestHeader.UserAgent interchangeably:
More info on using exceptions for flow control: https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why
If the User-Agent malformed, any kind of read on that header will always throw exception!