Skip to content

IT CSharp Keyword using

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: using

Manuale C# · Guida pratica

Importa nomi, imposta un alias o gestisce una risorsa IDisposable/IAsyncDisposable. L'importazione stessa non aggiunge la dipendenza mancante.

Esempio semplice (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
using System;
using (var stream = new System.IO.MemoryStream())
{
    stream.WriteByte(65);
    Console.WriteLine(stream.Length);
}

Risultato:

1

Sintassi

using Namespace; / using Alias = Type; / using var resource = ...; / await using ...;

la dichiarazione using è valida fino alla fine dell'ambito. Per .csx utilizzare using (...) { ... } se la dichiarazione di livello superiore è ambigua per la sintassi dello script.

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)
    {
        using var stream = new MemoryStream();
        stream.WriteByte(65);
        Console.WriteLine(stream.Length);
    }
}

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)
    {
        await using var stream = new MemoryStream();
        await stream.WriteAsync(new byte[] { 1, 2, 3 });
        Console.WriteLine(stream.Length);
    }
}

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally