Question

F# accepts the following:

type Abc =
    member this.A = 10

Since no parameter-list was supplied, there is no default constructor. Can a constructor be added to Abc? If not, what can be done with Abc?

Was it helpful?

Solution

I can't think of many uses for this, but two things you can do are

  1. inherit from it, albeit derived types must not be instantiable either
  2. extend it with static members (although this is better achieved with modules, which can also be extended)
type Abc =
    member this.A = 10

[<Class>]
type Def = 
    inherit Abc

type Abc with
    static member Foo() = ()

In C#, Code Contracts for an interface or abstract class are defined in a "contract class" which must be marked abstract and have a private constructor (i.e. it's non-instantiable). This, in my opinion, is a better way of accomplishing that. But C# doesn't support constructor-less classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top