I have a object in F# as follows…
type Person(?name : string) =
let name = defaultArg name ""
member x.Name = name
I want to be able to create an instance of this object in a C# project. I have added as a reference the correct libraries to the project and can see the object via intellisense however I am not sure on the correct syntaxt to create an instance of the object.
Currently I have the following in my C# project – which the compiler doesn’t like…
var myObj1 = new Person("mark");
To add some details, the F# compiler uses different approach for representing optional parameters, which is not (currently) compatible with the C# 4.0 approach. F# simply allows you to use a nicer syntax when the parameter has type
option<'a>(and is marked as optional). You can use it as it is, or you can use thedefaultArgfunction to provide default value in your code.In C#, the parameter is represented specially in the meta-data (.NET 4.0 specific feature), and the default value is specified in the meta-data. Unfortunately, there is no way to create C# 4.0 compatible optional parameter in F#.
If you want to make the C# code a little-bit nicer, you can define a static utility class that allows you to use type inference when creating
option<'a>values:Or you can modify your F# declaration to use overloaded methods/constructors, which works in both of the languages: