Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Constructors in f# with property assignment

Tags:

f#

I want to have a constructor that is blank and a constructor overload that accepts a parameter and assign it to a public property.

This is where I am stuck:

type TemplateService() = 
    interface ITemplateService with

        //Properties
        member TemplateDirectory = ""

        //Constructors
        new (templateDirectory:string) = //Error here.
            if (templateDirectory == null) then
                raise (new System.ArgumentNullException("templateDirectory"))
            TemplateDirectory = templateDirectory;

It gives me the error: `Unexpected keyword 'new' in the Object expression. Expected 'member', 'override' or other token.

If I use member, the property TemplateDirectory gives this error:

This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'

like image 517
Shawn Mclean Avatar asked Oct 23 '25 20:10

Shawn Mclean


1 Answers

You could try this.

type TemplateService(templateDirectory : string) = 
    do
        if templateDirectory = null then nullArg "templateDirectory"

    new() = TemplateService("")

    interface ITemplateService with
        member this.TemplateDirectory = templateDirectory
like image 173
Nyi Nyi Avatar answered Oct 26 '25 12:10

Nyi Nyi