Export (0) Print
Expand All

extern

Use the extern modifier in a method declaration to indicate that the method is implemented externally. A common use of the extern modifier is with the DllImport attribute. (See DllImportAttribute Class for more information.)

It is an error to use the abstract and extern modifiers together to modify the same member. Using the extern modifier means that the method is implemented outside the C# code, while using the abstract modifier means that the method implementation is not provided in the class.

Because an external method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:

public static extern int MyMethod(int x);
Note   The extern keyword is more limited in use than in C++. To compare with the C++ keyword, see Using extern to Specify Linkage in the C++ Language Reference.

For more information on external methods, see 10.5.7 External methods.

For more information on attributes, see 17. Attributes.

Example

In this example, the program receives a string from the user and displays it inside a message box. The program uses the MessageBox method imported from the User32.dll library.

using System;
using System.Runtime.InteropServices;
class MyClass 
{
   [DllImport("User32.dll")]
   public static extern int MessageBox(int h, string m, string c, int type);

   public static int Main() 
   {
      string myString; 
      Console.Write("Enter your message: ");
      myString = Console.ReadLine();
      return MessageBox(0, myString, "My Message Box", 0);
   }
}

Sample Run

Enter your message: Where do you want to go today?

When the previous text is entered, a message box that contains the text will pop up on the screen.

Example

This example uses two files, CM.cs and Cmdll.c, to demonstrate extern. The C file is an external DLL that is invoked from within the C# program.

File: Cmdll.c

// cmdll.c
// compile with: /LD /MD
int __declspec(dllexport) MyMethod(int i)
{
   return i*10;
}

File: CM.cs

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MyClass 
{
   [DllImport("Cmdll.dll")]
   public static extern int MyMethod(int x);
   public static void Main() 
   {
      Console.WriteLine("MyMethod() returns {0}.", MyMethod(5));
   }
}

Output

MyMethod() returns 50.

Compilation

To build the project, use the following steps:

  • Compile Cmdll.c to a DLL using the Visual C++ command line:
    cl /LD /MD Cmdll.c
    
  • Compile CM.cs using the command line:
    csc CM.cs
    

This will create the executable file CM.exe. When you run this program, MyMethod will pass the value 5 to the DLL file, which returns the value multiplied by 10.

See Also

C# Keywords | Modifiers

Show:
© 2015 Microsoft