Fun fact: C# methods whose bodies span over multiple source files 19 Jan 2012


While working on Mono.Cecil (your lovely library to analyze and manipulate .net binaries that is used by legions), one thing that struck me as odd for a while, was the fact that a method could have debug symbols for instructions that are defined in multiple files. Cecil has this type, Instruction. When you're analyzing a module with debug information (think .pdb or .mdb files), an Instruction may have its SequencePoint property set. A sequence point is nothing but the location of the code in a file that relates to the instruction. What got me wondering, is that the APIs to retrieve those sequence points make it so that a method can have sequence points in different documents. So be it, this is how I ended up representing it in Cecil, but it's only recently that I stumbled upon a case where indeed, a C# method had instructions defined in multiple files: Foo.Bar.cs:
public partial class Foo {
    private List _bars = new List();
}
Foo.Baz.cs:
public partial class Foo {
    private Baz _baz;

    public Foo (Baz baz)
    {
        _baz = baz;
    }
}
Do you see what's going on here? The constructor of Foo is defined in Foo.Baz.cs, but there's a field initializer in Foo.Bar.cs that is going to be compiled inside Foo's constructor. When you debug the constructor, you'll effectively end up jumping between the two files. Crazy right? Can you think of another case where a C# (or VB.NET for that matters) method would have instructions defined in different files?