C# and F# lambda expressions code generation

Posted by ControlFlow on Stack Overflow See other posts from Stack Overflow or by ControlFlow
Published on 2010-06-01T09:30:10Z Indexed on 2010/06/01 9:33 UTC
Read the original article Hit count: 524

Filed under:
|
|
|
|

Let's look at the code, generated by F# for simple function:

let map_add valueToAdd xs =
    xs |> Seq.map (fun x -> x + valueToAdd)

The generated code for lambda expression (instance of F# functional value) will looks like this:

[Serializable]
internal class map_add@3 : FSharpFunc<int, int> {
    public int valueToAdd;
    internal map_add@3(int valueToAdd) { this.valueToAdd = valueToAdd; }
    public override int Invoke(int x)  { return (x + this.valueToAdd); }
}

And look at nearly the same C# code:

using System.Collections.Generic;
using System.Linq;

static class Program {
    static IEnumerable<int> SelectAdd(IEnumerable<int> source, int valueToAdd) {
        return source.Select(x => x + valueToAdd);
    }
}

And the generated code for the C# lambda expression:

[CompilerGenerated]
private sealed class <>c__DisplayClass1 {
    public int valueToAdd;
    public int <SelectAdd>b__0(int x) { return (x + this.valueToAdd); }
}

So I have some questions:

  • Why does F#-generated class is not marked as sealed?
  • Why does F#-generated class contains public fields since F# doesn't allows mutable closures?
  • Why does F# generated class has the constructor? It may be perfectly initialized with the public fields...
  • Why does C#-generated class is not marked as [Serializable]? Also classes generated for F# sequence expressions are also became [Serializable] and classes for C# iterators are not.

© Stack Overflow or respective owner

Related posts about c#

Related posts about serialization