How does extern work in C#?

Consider reading section 10.6.7 of the C# specification, which answers many of your questions. I reproduce part of it here for your convenience:


When a method declaration includes an
extern modifier, that method is said
to be an external method. External
methods are implemented externally,
typically using a language other than
C#. Because an external method
declaration provides no actual
implementation, the method-body of an
external method simply consists of a
semicolon. An external method may not
be generic. The extern modifier is
typically used in conjunction with a
DllImport attribute,
allowing external methods to be
implemented by DLLs (Dynamic Link
Libraries). The execution environment
may support other mechanisms whereby
implementations of external methods
can be provided. When an external
method includes a DllImport attribute,
the method declaration must also
include a static modifier.


How does someone leverage the extern attribute?

  • Write your code in the unmanaged language of your choice.
  • Compile it into a DLL, exporting the entry point of your code.
  • Make an interop library that defines the method as an extern method in the given DLL.
  • Call it from C#.
  • Profit!

How would I go about looking into the source of extern methods like Object.InternalGetEquals()?

Go to https://github.com/dotnet/coreclr/tree/master/src/vm

Leave a Comment