Operatore new (riferimenti per C#)new operator (C# reference)
L'operatore new
consente di creare una nuova istanza di un tipo.The new
operator creates a new instance of a type.
È anche possibile usare la parola chiave new
come modificatore di dichiarazione di membro o come vincolo di tipo generico.You can also use the new
keyword as a member declaration modifier or a generic type constraint.
Chiamata di un costruttoreConstructor invocation
Per creare una nuova istanza di un tipo, in genere si chiama uno dei costruttori del tipo in questione tramite l'operatore new
:To create a new instance of a type, you typically invoke one of the constructors of that type using the new
operator:
var dict = new Dictionary<string, int>();
dict["first"] = 10;
dict["second"] = 20;
dict["third"] = 30;
Console.WriteLine(string.Join("; ", dict.Select(entry => $"{entry.Key}: {entry.Value}")));
// Output:
// first: 10; second: 20; third: 30
È possibile usare un inizializzatore di oggetto o insieme con l'operatore new
per creare un'istanza di un oggetto e inizializzare l'oggetto in un'unica istruzione, come illustrato nell'esempio seguente:You can use an object or collection initializer with the new
operator to instantiate and initialize an object in one statement, as the following example shows:
var dict = new Dictionary<string, int>
{
["first"] = 10,
["second"] = 20,
["third"] = 30
};
Console.WriteLine(string.Join("; ", dict.Select(entry => $"{entry.Key}: {entry.Value}")));
// Output:
// first: 10; second: 20; third: 30
A partire da C# 9,0, le espressioni di chiamata del costruttore sono tipizzate come destinazione.Beginning with C# 9.0, constructor invocation expressions are target-typed. Ovvero, se un tipo di destinazione di un'espressione è noto, è possibile omettere un nome di tipo, come illustrato nell'esempio seguente:That is, if a target type of an expression is known, you can omit a type name, as the following example shows:
List<int> xs = new();
List<int> ys = new(capacity: 10_000);
List<int> zs = new() { Capacity = 20_000 };
Dictionary<int, List<int>> lookup = new()
{
[1] = new() { 1, 2, 3 },
[2] = new() { 5, 8, 3 },
[5] = new() { 1, 0, 4 }
};
Come illustrato nell'esempio precedente, si usano sempre le parentesi in un'espressione tipizzata di destinazione new
.As the preceding example shows, you always use parentheses in a target-typed new
expression.
Se un tipo di destinazione di un' new
espressione è sconosciuto (ad esempio, quando si usa la var
parola chiave), è necessario specificare un nome di tipo.If a target type of a new
expression is unknown (for example, when you use the var
keyword), you must specify a type name.
creazione di matriciArray creation
È possibile usare l'operatore new
per creare un'istanza di matrice, come illustrato nell'esempio seguente:You also use the new
operator to create an array instance, as the following example shows:
var numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
Console.WriteLine(string.Join(", ", numbers));
// Output:
// 10, 20, 30
Usare la sintassi di inizializzazione di una matrice per creare un'istanza di una matrice e popolarla con elementi in un'unica istruzione.Use array initialization syntax to create an array instance and populate it with elements in one statement. L'esempio seguente illustra diversi modi per eseguire questa operazione:The following example shows various ways how you can do that:
var a = new int[3] { 10, 20, 30 };
var b = new int[] { 10, 20, 30 };
var c = new[] { 10, 20, 30 };
Console.WriteLine(c.GetType()); // output: System.Int32[]
Per altre informazioni sulle matrici, vedere Matrici.For more information about arrays, see Arrays.
Creazione di istanze di tipi anonimiInstantiation of anonymous types
Per creare un'istanza di un tipo anonimo, usare l'operatore new
e la sintassi dell'inizializzatore di oggetto:To create an instance of an anonymous type, use the new
operator and object initializer syntax:
var example = new { Greeting = "Hello", Name = "World" };
Console.WriteLine($"{example.Greeting}, {example.Name}!");
// Output:
// Hello, World!
Eliminazione di istanze di tipiDestruction of type instances
Non è necessario eliminare definitivamente istanze di tipi create in precedenza.You don't have to destroy earlier created type instances. Le istanze dei tipi riferimento e valore vengono eliminate definitivamente in modo automatico.Instances of both reference and value types are destroyed automatically. Le istanze dei tipi valore vengono eliminate definitivamente non appena viene eliminato definitivamente il contesto che le contiene.Instances of value types are destroyed as soon as the context that contains them is destroyed. Le istanze dei tipi di riferimento vengono distrutte dal Garbage Collector in un momento non specificato dopo che è stato rimosso l'ultimo riferimento.Instances of reference types are destroyed by the garbage collector at some unspecified time after the last reference to them is removed.
Per le istanze di tipo che contengono risorse non gestite, ad esempio un handle di file, è consigliabile usare la pulizia deterministica per assicurarsi che le risorse che contengono siano rilasciate il prima possibile.For type instances that contain unmanaged resources, for example, a file handle, it's recommended to employ deterministic clean-up to ensure that the resources they contain are released as soon as possible. Per altre informazioni, vedere le informazioni di riferimento dell'API System.IDisposable e l'articolo sull' istruzione using .For more information, see the System.IDisposable API reference and the using statement article.
Overload degli operatoriOperator overloadability
Un tipo definito dall'utente non può eseguire l'overload dell'operatore new
.A user-defined type cannot overload the new
operator.
Specifiche del linguaggio C#C# language specification
Per altre informazioni, vedere la sezione Operatore new della specifica del linguaggio C#.For more information, see The new operator section of the C# language specification.
Per ulteriori informazioni su un'espressione tipizzata di destinazione new
, vedere la Nota relativa alla proposta di funzionalità.For more information about a target-typed new
expression, see the feature proposal note.