Var keyword in C # programming

0
72

1. CHARACTERISTICS OF THE KEYWORD VAR

From .Net 3.0 Microsoft has added the var keyword to the library of keywords in .Net Programming.
Var keyword supports initializing variables and arrays without declaring the data type, the data type will be determined when assigning the value to the variable, at this time the program will automatically cast the variable. And of course, after assigning values, those variables and arrays have a defined data type and cannot be changed. See the example below, we have 3 variables declared with the keyword var. In turn, 3 variables are assigned values ​​with data types as int, char, string. After assigning values ​​the variables are used like normal variables

2. SOME NOTES:

  • Do not use var to declare data types for properties (properties) as well as the return values ​​of methods in the class.
  • Must assign values ​​to variables using the var type immediately initializing variables (assigning values ​​right in the command line initializing variables: var a = 1;) Here we can see that if it is required to assign such values, the failure Need to declare the data type as meaningless. Here we have assigned a null value to the variable var at initialization to avoid generating errors.

3. DECLARE ARRAYS WITH VAR KEYWORD:

We can use the var keyword to declare an unspecified array of data types as in the example below. We see with this declaration when browsing the array we do not care what the data type of each element in the array is, just use the foreach loop with a var variable to find all the elements in the array. We find this approach very convenient, we do not need to care how many arrays of elements to count the number of times the loop.

4. VAR APPLICATION IN THE TREATMENT OF ArrayList
The example below shows the advantage of var when no predefined data types for variables are known. Initially, we created one list and in turn assign the data as 1, 2, Three, Four. Then use a foreach loop to browse the elements in the list, but this list is initialized with two types of values, therefore it is difficult to browse the list. But if you use the var then everything becomes very easy, because no matter what the data type is, the program will automatically cast.
Var keyword in C # programming

5. APPLICATION OF VAR IN LINQ:

In the example below, we see a very nice application for var in Linq queries. Using just one var variable can store all the values ​​returned from the query and then use foreach (var) to retrieve the values.

Var keyword in C # programming

 

 

At this point, we can see very convenient features when using the var keyword, if you apply it appropriately, you will have the optimal code, with high generality, applicable in many types. different data.

Leave A Reply

Please enter your comment!
Please enter your name here