Search code examples
c#internals

If Int32 is just an alias for int, how can the Int32 class use an int?


Been browsing through .NET source code of .NET Framework Reference Source, just for fun of it. And found something I don't understand.

There is a Int32.cs file with C# code for Int32 type. And somehow that seems strange to me. How does the C# compiler compile code for Int32 type?

public struct Int32: IComparable, IFormattable, IConvertible {
    internal int m_value;

    // ... 
}

But isn't this illegal in C#? If int is only an alias for Int32, it should fail to compile with Error CS0523:

Struct member 'struct2 field' of type 'struct1' causes a cycle in the struct layout.

Is there some magic in the compiler, or am I completely off track?


Solution

  • isn't this illegal in C#? If "int" is only alias for "Int32" it should fail to compile with error CS0523. Is there some magic in the compiler?

    Yes; the error is deliberately suppressed in the compiler. The cycle checker is skipped entirely if the type in question is a built-in type.

    Normally this sort of thing is illegal:

    struct S { S s; int i; }
    

    In that case the size of S is undefined because whatever the size of S is, it must be equal to itself plus the size of an int. There is no such size.

    struct S { S s; }
    

    In that case we have no information from which to deduce the size of S.

    struct Int32 { Int32 i; }
    

    But in this case the compiler knows ahead of time that System.Int32 is four bytes because it is a very special type.

    Incidentally, the details of how the C# compiler (and, for that matter, the CLR) determines when a set of struct types is cyclic is extremely interesting. I'll try to write a blog article about that at some point.