Skip to content

IT CSharp Keyword extern

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: extern

Manuale C# · Guida pratica

Dichiara un membro implementato al di fuori del codice C#; tipico per l'interoperabilità nativa tramite DllImport. alias esterno specifica un alias di assembly esterno.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

Example.cs:

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

Solo dichiarazione: il codice si compila come libreria; per eseguirlo serve una chiamata da Main.

Sintassi

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

Questi due esempi nativi sono per Windows. Il nome della libreria, ABI e la disponibilità delle funzionalità dipendono dalla piattaforma; la compilazione stessa non ne verifica la presenza.

Esempio 1: forma base

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(); }

Esempio 2: un'altra forma pratica

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(); }

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally