NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

extern

Use the extern modifier in method declaration to indicate that the method is implemented externally. A common use of the extern modifier is with the dllimport attribute.

Remarks

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.

The body of the method with the extern modifier is only a semicolon, 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 extern in the C++ Language Reference.

For more information on external methods, see External Methods in the Language Reference.

For more information on attributes, see Attributes in the Language Reference.

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 exported from User32.DLL.

// The extern modifier
using System;
class MyClass {
   [sysimport(dll = "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?

After you have entered the previous text, a message box that contains this 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, which is invoked from within the C# program.

File: CM.cs

using System;
public class MyClass {
   [sysimport(dll="cmdll",name="MyMethod")]
   public static extern int MyMethod(int x);
   public static void Main() {
      Console.WriteLine("MyMethod() returns {0}.",MyMethod(5));
   }
}

File: Cmdll.c

int __declspec(dllexport) MyMethod(int i) {
   return i*10;
}

Compilation

To build the project use the following steps:

Output

MyMethod() returns 50.

See Also

C# Keywords | Modifiers