On the usage of var keyword in c

  • 2020-05-24 06:03:22
  • OfStack

VAR is a new definition of the variable type in 3.5
In other words, weaken the definition of a type
VAR can substitute for any type
The compiler will determine what type you want to use based on the context

As for when to use VAR, I think you are not sure what type you are going to use
You can use VAR like OBJECT
But it's more efficient than OBJECT

Using var to define variables has the following four characteristics:
1. Must be initialized at definition time. So it has to be var s = "abcd" form, not the following form:
var s;
s = "abcd";
2.1 but once the initialization is complete, you can no longer assign a variable a value of a different type than the initialization value.
3. var is required to be a local variable.
4. Using var to define variables is different from object in that it is exactly the same in efficiency as using strongly typed methods to define variables.

The var keyword is a new feature that has been added to C# 3.5, called inferred types.
You can assign local variables to infer "types" var instead of explicit types. The var keyword instructs the compiler to infer the type of the variable based on the expression to the right of the initialization statement. Inferred types can be built-in types, anonymous types, user-defined types, types defined in the.NET Framework class library, or any expression.
The above information is a little abstract and hard to understand.
Example:
The original definition of a variable was:
Data type variable name = value;
Such as:
int a = 1;
string b = "2";
In other words," you have to specify explicitly "what data type your variable is before you can assign it a value.
Now in C# 3.5, there is a change so that you don't have to define variables as you did above.
Such as:
var a =1 ;
So what is this a? It's not the same as it was before.
Here's the trick: IDE or the compiler will "infer" that a is an integer type based on the value you gave a :1.
In the same way:
var b = "2";
Since the value given to b is a string like "2",b is of type string...


Related articles: