C # var keyword detailed
var is the 3.5 new type that defines a variable in fact, that is, the definition of a weakening type Var can replace any type of compiler that will judge you by context. What kind of case would you like to use Var? I think you're not sure what type you're going to use. var is similar Object but more efficient than object.
Or in layman's terms:
var can be understood as an anonymous type, and we can think of it as a placeholder for declaring a variable. It is used primarily when declaring a variable and cannot determine the data type.
The following four features are used to define variables using var:
1. Must be initialized at the time of definition. That is, it must be var s = "ABCD" form, not the following form: Var s; s = "ABCD";
2. Once the initialization is complete, the variable can no longer be assigned a different value than the initialization value type.
3. The var requirement is a local variable.
4. By using the var definition variable and object, it is exactly the same in terms of efficiency and the use of a strongly typed method to define variables.
Instance:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Namespace Firstpriject
{
class program
{
static void Main (string[] args)
{
//Declaration and initialization of variables
var name = "John";
var age = ten;
var sex = true;
Gets the variable's data type type
T_name = Name. GetType ();
Type T_age = age. GetType ();
Type t_sex = Sex. GetType ();
Print result
Console.WriteLine (the type of variable Name is {0}, the type of variable age is {1}, the type of variable sex is {2} ",
t_name.tostring (), t_age.tostring (), t_sex.tostring ());
Do not automatically close the console, waiting for input
console.readline ();}}
Example result diagram:
Thank you for reading, I hope to help you, thank you for your support for this site!