1

I'm sure this is simple but I can't find an explanation.

When disassembling .net with ILSpy or ILDASM there is a class named <module> in the default namespace.

Why and how the compiler puts it there? I have this:

using abc;
using System;

internal class <Module>
{
    static <Module>()
    {
        AssemblyLoader.Attach();
    }
}
internal interface ISomething
{
}

This is not the standart declaration. If I'm recreating C# project how would I add that? Also the way I see it it is in a static constructor and will get executed before the entrypoint, so if I put AssemblyLoader.Attach(); in my Main() or in a static constructor of Program (I'm using console app template) this should do the trick, right?

JDOE
  • 45
  • 4
  • [C# - Understand the class name add <> symbol](http://stackoverflow.com/questions/19615662/how-to-understand-the-class-name-add-symbol) – Sen Jacob Dec 13 '16 at 10:08
  • [Module initializers in C#](http://stackoverflow.com/a/17379410/399414) – Sen Jacob Dec 13 '16 at 10:12
  • That is illegal syntax for C#, but not for IL. The compiler generates these kinds of implicit classes all the time for a multitude of reasons. The short answer is, no, you cannot recreate that. – Abion47 Dec 13 '16 at 10:12
  • Yes I understand why it is called that way, I wander how to make the compiler output the same thing though.. – JDOE Dec 13 '16 at 10:12
  • Well how to implement that call in my project - AssemblyLoader.Attach(); – JDOE Dec 13 '16 at 10:13

1 Answers1

3

You can't add code directly to <Module> from the VS or C# code. You can do it from the IL.

If you disassemble your code you can put a static .cctor which would end up being the <Module> constructor. It has to be outside any .class

.method private hidebysig specialname rtspecialname static void .cctor () cil managed 
{
    //put your code here
}

You can see an example in my repo on github.

Or use Fody's tool and particularly ModuleInit.

Paweł Łukasik
  • 3,893
  • 1
  • 24
  • 36
  • I understand but I would like to do this in my C# code. I don't need to produce the same output, I just need the method to be called appropriately – JDOE Dec 13 '16 at 11:50
  • @JODE - the closes thing to C# is to use Fody. There you can mark one of your C# method to be injected into the module. But it's still done the same way - just you don't need to know the details how it's done. – Paweł Łukasik Dec 13 '16 at 11:54