Skip to content

EN CSharp Keyword extern

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: extern

Handbook C# · Practical Guide

Declares a member implemented outside the C# code; typical for native interop via DllImport. extern alias specifies an external assembly alias.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
class NativeMethods
{
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    public static extern uint GetCurrentProcessId();
}

Declaration only: this code compiles as a library; call it from Main to run it.

Syntax

[DllImport(...)] public static extern ReturnType Method(...);

These two native examples are for Windows. Library name, ABI and feature availability are platform dependent; the compilation itself does not check for their presence.

Example 1: simple form

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetCurrentProcessId());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId(); }

Example 2: another practical form

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetTickCount64());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static extern ulong GetTickCount64(); }

Official source: Microsoft Learn.

Clone this wiki locally