Search code examples
c#f#delegatesfirst-class-functions

What is the difference between delegates in C# and functions as first class values in F#?


More specifically what are the characteristics (if any) that delegates have that functions as first class values in F# don't have; and what are the characteristics that functions as first class values have (if any) that delegates in C# don't have?


Solution

  • Delegates and F# "First class function values" are quite different.

    Delegates are a mechanism of the CLR, a type-safe wrapper around function-pointer+object pairs (for instance methods, the this-pointer gets captured together with the method address).

    F# function values on the other hand, are implementation of an abstract class FSharpFunc<,> (it used to be called FastFunc<,> before the official release of F#). Invocation happens via ordinary virtual methods, which is much faster than delegate invocation. That is the reason the F#-team didn't use delegates in the first place.

    So if you can "implement" functions as first class values via abstract classes/virtual methods, why did Microsoft add delegates?

    • There was no alternative In .NET 1.0/1.1, there were no generics, so you had to define a new delegate type (="function type") for every function signature you wanted to use.
    • (No, just using interfaces like in Java doesn't count. :-P )

    Ok, but we have Generics since .NET 2.0, why do we still have delegates? Why can't we just use Func<,> and Action<> for everything?

    • Backwards compatibility
    • Multicast Delegates Delegates can be chained together to form new delegates. This mechanism is used to implement events in VB.NET and C#. Behind the scenes, an event is really just a single delegate field. Using the += syntax you essentially add your event-handler-delegate to the chain of delegates in the event field.

    Apart from events, is there a reason to use delegates over FSharpFunc<,>

    Yes, one: Each and every implementation of FSharpFunc<,>, that includes lambda-expressions*, is a new class. And in .NET classes are encoded in the metadata of the compiled assembly. Delegates on the other hand require no extra metadata. The delegate types do but instantiating these delegate types is free in terms of metadata.

    But wait, aren't C# lambda-expressions/anonymous methods too implemented as hidden classes?

    Yes, C# lambdas take the worst of both worlds ^^