var (riferimenti per C#)var (C# reference)
A partire da C# 3, le variabili dichiarate nell'ambito del metodo possono avere un "tipo" implicito var
.Beginning with C# 3, variables that are declared at method scope can have an implicit "type" var
. Una variabile locale tipizzata in modo implicito è fortemente tipizzata come se si fosse dichiarato il tipo stesso, ma è il compilatore a determinare il tipo.An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. Le due dichiarazioni seguenti di i
sono equivalenti dal punto di vista funzionale:The following two declarations of i
are functionally equivalent:
var i = 10; // Implicitly typed.
int i = 10; // Explicitly typed.
Importante
Quando var
viene usato con i tipi di riferimento Nullable abilitati, implica sempre un tipo di riferimento Nullable anche se il tipo di espressione non ammette i valori null.When var
is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable.
Un uso comune della var
parola chiave è con espressioni di chiamata del costruttore.A common use of the var
keyword is with constructor invocation expressions. L'uso di var
consente di non ripetere un nome di tipo in una dichiarazione di variabile e un'istanza dell'oggetto, come illustrato nell'esempio seguente:The use of var
allows you to not repeat a type name in a variable declaration and object instantiation, as the following example shows:
var xs = new List<int>();
A partire da C# 9,0, è possibile usare un' new
espressione tipizzata di destinazione come alternativa:Beginning with C# 9.0, you can use a target-typed new
expression as an alternative:
List<int> xs = new();
List<int>? ys = new();
Nei criteri di ricerca la var
parola chiave viene usata in un var
modello.In pattern matching, the var
keyword is used in a var
pattern.
EsempioExample
L'esempio seguente illustra due espressioni di query.The following example shows two query expressions. Nella prima espressione l'uso di var
è consentito, ma non necessario, perché il tipo del risultato della query può essere dichiarato in modo esplicito come IEnumerable<string>
.In the first expression, the use of var
is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>
. Nella seconda espressione, tuttavia, var
consente che il risultato sia una raccolta di tipi anonimi e il nome di tale tipo non è accessibile tranne che al compilatore stesso.However, in the second expression, var
allows the result to be a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. L'uso di var
elimina la necessità di creare una nuova classe per il risultato.Use of var
eliminates the requirement to create a new class for the result. Si noti che nel secondo esempio anche la variabile di iterazione foreach``item
deve essere tipizzata in modo implicito.Note that in Example #2, the foreach
iteration variable item
must also be implicitly typed.
// Example #1: var is optional when
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
where word[0] == 'g'
select word;
// Because each element in the sequence is a string,
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
Console.WriteLine(s);
}
// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
where cust.City == "Phoenix"
select new { cust.Name, cust.Phone };
// var must be used because each item
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}