Cook Computing

IL Trivia

September 5, 2003 Written by Charles Cook

I listened to the Brent Rector edition of .NET Rocks on the drive to London on Wednesday morning and one trivial point stuck in my mind. It turns out that .NET types can have multiple fields with the same name, as long as the type of each field is different. For example the following class builds ok:


.assembly extern mscorlib {}
.assembly demo {}
.module demo.dll

.class public DemoClass
{
    .method public hidebysig specialname rtspecialname
        instance void  .ctor() cil managed
    {
        .maxstack  1
        IL_0000:  ldarg.0
        IL_0001:  call  instance void [mscorlib]System.Object::.ctor()
        IL_0006:  ret
    }

    .field public bool myvar
    .field public int32 myvar
    .field public string myvar
}

C# is obviously going to have problems with this but you can actually use the class from C# as long as you assume the type of myvar is the type specified in the first definition of the field in the class, bool in this case. For example, the following program compiles:


class _
{
    static void Main()
    {
        DemoClass dc = new DemoClass();
        dc.myvar = true;
    }
}

I don't know whether this is a quirk of the compiler or prescribed behaviour. Brent explained that this feature of IL is the basis of one of the obfuscation techniques used in his Demeanor product, to make it harder for decompilers to produce C# code from a .NET assembly.

Another interesting point about Demeanor was that it strips out unnecessary symbols and metadata, resulting in a substantial reduction in the size of the assembly being obfuscated.