Extern Methods

One other type of method declaration supported by C# is an extern method. Basically, it enables you to specify a method whose definition lives somewhere else. This sounds rather vague, and indeed it is, as the runtime has to come in to help and find the target implementation for the method. Basically, the only directly applicable scenario for end users is the technique of P/Invoke, where one bridges to a method defined in unmanaged code (for example, in a Win32 API). The following piece of code shows this in practice:

public static void Main(string[] args){    int size = 0;    var user = new StringBuilder(size);    if (!GetUserName(user, ref size))    {        var error = Marshal.GetLastWin32Error();        if (error != ERROR_INSUFFICIENT_BUFFER) ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.