F# object initializer syntax not working for simple case

Viewed 65

In C#, this object initialization syntax works perfectly fine:

using System.Net;
var p = new WebProxy{Address = new Uri("http://127.0.0.1:1234")};

To my understanding, the equivalent to such syntax in F# should look like below:

open System
open System.Net
let proxy = new WebProxy( Address = Uri("http://127.0.0.1:1234") )

However, it fails with:

error FS0041: A unique overload for method 'WebProxy'
could not be determined based on type information prior
to this program point. A type annotation may be needed.

Known type of argument: Address: Uri

Candidates:
 - WebProxy() : WebProxy
 - WebProxy(Address: Uri) : WebProxy

Questions:

  1. Why doesn't it work? The error messages seems to suggest it cannot decide between the no-parameter version and single-parameter version, but why?
  2. How do I add type annotations so that the above will compile?
1 Answers

I think that the error is only happening in the case because the constructor has a parameter Address and the type also had a property Address. In F#, named parameters have the same syntax as a object initialization, so it doesn't know which feature to use.

This is an unusual clash because parameter names are usually camelCase, not PascalCase. One simple fix in this case is to use an unnamed parameter instead of object initializer:

let proxy = WebProxy(Uri("http://127.0.0.1:1234"))
Related