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.
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.
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); } }
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.
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.
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)); } }
int __declspec(dllexport) MyMethod(int i) { return i*10; }
To build the project use the following steps:
Cmdll.c
to a DLL using the Visual C++ command line:
cl /LD /MD cmdll.c
CM.cs
file using the command line:
csc CM.cs
CM.exe
. When you run this program, MyMethod
will pass the value 5 to the DLL file, which returns the value multiplied by 10.MyMethod() returns 50.