Search code examples
c#.netcompiler-constructioncircular-referenceself-reference

c# - How do self-referencing classes or circular-referencing classes within same assembly compile successfully


I would like to know how C# and .Net compiler is able to successfully compile a self-referenced class or circular referenced classes within same assembly.

Consider the following code is present within the same assembly.

class X{ X x; }
class Y{ Z z; }
class Z{ Y y; }

Of course, this code compiles successfully.
But How? I'd like to know is how the compiler is able to resolve the classes in these cases for the very first time.
For example, when the compiler encounters class Y, it does not know class Z yet. How is it able to resolve the child property z in Class Y?
Please explain what exactly happens in the background when the code is compiled. Probably some suitable articles on how compiler resolves classes and types


Solution

  • As mentioned in this article, C# compiler performs "Two Pass" i.e.

    1. In first pass it computes metadata: the “top level” stuff, like namespaces, classes, structs, enums, interfaces, delegates, methods, type parameters, formal parameters, constructors, events, attributes, and so on.

    2. The second pass computes the IL: the code that goes in the method bodies, constructor bodies, and so on.

    C# compilation approach is different from C/C++, where class, method, macros etc are declared in header files, which helps it gain all information about class, methods etc in one pass just by reading header files. In comparison to C# it does not have header files, instead it uses Two Pass technique to compile all the code.