C# Programming/Keywords/extern

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The keyword extern indicates that the method being called exists in a DLL.

A tool called tlbimp.exe can create a wrapper assembly that allows C# to interact with the DLL like it was a .NET assembly i.e. use constructors to instantiate it, call its methods.

Older DLLs will not work with this method. Instead, you have to explicitally tell the compiler what DLL to call, what method to call and what parameters to pass. Since parameter type is very important, you can also explicitly define what type the parameter should be passed to the method as.

Here is an example:

using System;
using System.Runtime.InteropServices;

namespace ExternKeyword
     public class Program
          static void Main()
               NativeMethods.MessageBoxEx(IntPtr.Zero, "Hello there", "Caption here", 0, 0);
     public class NativeMethods
          public static extern MessageBoxEx(IntPtr hWnd, string lpText, string lpCaption, uint uType, short wLanguageId);

The [DllImport("user32.dll")] tells the compiler which DLL to reference. Windows searches for files as defined by the PATH environment variable, and therefore will search those paths before failing.

The method is also static because the DLL may not understand how to be "created", as DLLs can be created in different languages. This allows the method to be called directly, instead of being instantiated and then used.

C# Keywords
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
Special C# Identifiers (Contextual Keywords)
add alias async await dynamic
get global nameof partial remove
set value when where yield
Contextual Keywords (Used in Queries)
ascending by descending equals from
group in into join let
on orderby select where