inquam
inquam

Reputation: 12932

Is it possible for a F# type to "inherit" from a C# class?

I have used Haskell a bit in my days but it was a long time ago so I decided to take a look at F#. I do a lot of daily development using C, C++ and C#.

I noticed that you could expose F# types as classes in C# when compiling F# to a dll. But then I came to think. I have a few C# classes I would like to put the logic of in F# (to try it out). But a lot of the existing C# code handles a lot of objects by their base class (which is very rudimentary). Would it be possible to use that base class from C# as a base for the F# types? Or can F# only inherit from other F# types?

The reason behind this would be to keep the base class as part of the main C# project and the specific dlls (kind of like plugins based on the given contract by the base class) could be written in F#. If it can't be done I would have to add yet another F# project that contains only the base class which feels a bit overly complicated.

Upvotes: 7

Views: 2112

Answers (2)

Joh
Joh

Reputation: 2380

F# classes can inherit from .NET classes:

type FSharpClass() =
    inherit System.AccessViolationException()

Some other F# types such as records, discriminated unions cannot inherit from classes, but they can implement interfaces:

type FSharpRecord =
    { d : System.IDisposable }
    interface System.IDisposable with
        member this.Dispose() = this.d.Dispose()

Upvotes: 6

Justin Niessner
Justin Niessner

Reputation: 245399

Yes. It is possible.

type SomeClass =
    inherit SomeCSharpBase

Here are some more details:

Inheritance (F#)

Upvotes: 12

Related Questions