Wednesday, September 26, 2018

The elegance of a F# WebRequest

Love the elegance of doing a WebRequest in F#

module WebLoader =
    open System.Net
    open System.IO

    let GetString (url:string) =
        let request = WebRequest.Create(url)
        use response = request.GetResponse()
        use stream = response.GetResponseStream()
        use reader = new StreamReader(stream)

Especially the use keyword compared to the C# using { } blocks. Me like!


  1. Big F# fan here myself... But FWIW, you don't need any of the {}'s or tab-crawl in C# except for the last one. Two are two ways to do this:

    Multiple adjoined usings: (the way I prefer)

    using(var request = ...)
    using(var response = ...)
    { reader.ReadToEnd(); }

    or a comma separated like:

    using(var request = ...,
    var response = ...,
    { reader.ReadToEnd(); }

    1. Of course, that is true but after having coded with curly brackets for some 20 years in different c-like languages it is nice to get rid of them altogether :)
      Thanks for commenting!