extern


The extern keyword has two uses. Each of these is examined in turn.

Declaring extern Methods

The first use of extern indicates that a method is provided by unmanaged code that is sourced externally. A method is declared as extern by preceding its declaration with the extern modifier. The declaration must not include a body. The general form of an extern declaration is as follows.

extern return-type method-name(argument-list);

extern is often used with the attribute DllImport, which specifies the DLL that contains the method. DllImport is in the namespace System.Runtime.InteropServices.

Declaring an extern Assembly Alias

A second form of extern provides an alias for an assembly that is referenced. It is used when a program includes two assemblies that both contain the same name. For example, assembly Extern1 could contain a definition of class X and assembly Extern2 could contain a definition of the same class. A third assembly can differentiate between the two versions of class X using an assembly alias of the following form.

alias-name.X

The following example consists of three assemblies - two .dll's and a .exe. The dll's are Extern1.dll and Extern2.dll. Each of these have aliases Alias1 and Alias2 (respectively) defined. These aliases are defined in the properties of a reference that is included. Extern3.exe has two references defined each with their respective aliases.

The program code for Extern1.dll is shown below.

// Extern1 - The first part of the extern demo

using System;

namespace NameSpace
{
    public class X
    {
        public X()
        {Console.WriteLine("In Extern1 X Constructor");}
    }
    
}

The program code for Extern2.dll is shown below.

// Extern2 - The second part of the extern demo

using System;

namespace NameSpace
{
    public class X
    {
        public X()
        { Console.WriteLine("In Extern2 X Constructor"); }
    }

}

The program code for Extern3.exe is shown below.

// Extern3 - The Final Part of the extern demo

extern alias Alias1;
extern alias Alias2;

using System;

class Program
{
    static void Main()
    {
        Alias1.NameSpace.X x = new Alias1.NameSpace.X();
        Alias2.NameSpace.X y = new Alias2.NameSpace.X();
    }
}

The aliases defined at compile time are referenced through the extern statements at the top of the program. Within Main(), the two different class X's are differentiated using the alias name of the assembly. The output of the program (Extern3) is shown below.

In Extern1 X Constructor
In Extern2 X Constructor