Anything C# can do...

A whirlwind tour of object-oriented code in F#

As should be apparent, you should generally try to prefer functional-style code over object-oriented code in F#, but in some situations, you may need all the features of a fully fledged OO language ? classes, inheritance, virtual methods, etc.

So just to conclude this section, here is a whirlwind tour of the F# versions of these features.

Some of these will be dealt with in much more depth in a later series on .NET integration. But I won't cover some of the more obscure ones, as you can read about them in the MSDN documentation if you ever need them.

Classes and interfaces ##

First, here are some examples of an interface, an abstract class, and a concrete class that inherits from the abstract class.

// interface
type IEnumerator<'a> = 
    abstract member Current : 'a
    abstract MoveNext : unit -> bool 

// abstract base class with virtual methods
[<AbstractClass>]
type Shape() = 
    //readonly properties
    abstract member Width : int with get
    abstract member Height : int with get
    //non-virtual method
    member this.BoundingArea = this.Height * this.Width
    //virtual method with base implementation
    abstract member Print : unit -> unit 
    default this.Print () = printfn "I'm a shape"

// concrete class that inherits from base class and overrides 
type Rectangle(x:int, y:int) = 
    inherit Shape()
    override this.Width = x
    override this.Height = y
    override this.Print ()  = printfn "I'm a Rectangle"

//test
let r = Rectangle(2,3)
printfn "The width is %i" r.Width
printfn "The area is %i" r.BoundingArea
r.Print()

Classes can have multiple constructors, mutable properties, and so on.

Generics ##

F# supports generics and all the associated constraints.

Structs ##

F# supports not just classes, but the .NET struct types as well, which can help to boost performance in certain cases.

Exceptions ##

F# can create exception classes, raise them and catch them.

Extension methods ##

Just as in C#, F# can extend existing classes with extension methods.

Parameter arrays ##

Just like C#'s variable length "params" keyword, this allows a variable length list of arguments to be converted to a single array parameter.

Events ##

F# classes can have events, and the events can be triggered and responded to.

Delegates ##

F# can do delegates.

Enums ##

F# supports CLI enums types, which look similar to the "union" types, but are actually different behind the scenes.

Working with the standard user interface ##

Finally, F# can work with the WinForms and WPF user interface libraries, just like C#.

Here is a trivial example of opening a form and handling a click event.

Last updated

Was this helpful?