Var Keyword in C# Programming

1. Characteristics of the var keyword

In .Net 3.0 Microsoft added the var keyword in the keyword library of .Net. programming.

The "var" keyword initializes variables with var support. The data type of a var variable will be determined when assigning values ​to variables. The following program will automatically cast the variable. And of course, after assigning the variable value, the variable has a defined data type and cannot be replaced. In the example below we have 3 variables declared with the var keyword. In turn 3 variables are assigned values ​​with the data types int, char and string. After assigning values ​​to variables it can be used as ordinary variables.

001-keyword-var-microsofttech.net.jpg

2. A few notes

Do not use var to declare the data type for the property (properties) as well as the return type of the method (method) in the class.

The correct type must be used to initialize var variables to assign values ​​to variables.

3. Declare the array with the var keyword

We can use the var keyword to declare array data types where we don't have predefined datatypes as shown in the example below. We see here how declaring an array with a var datatype does not bother us with the type of data of each element in the array. Just use a foreach loop with one var variable to find all the elements in the array. 

002-keyword-var-microsofttech.net.jpg

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, hence 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.

003-keyword-var-microsofttech.net.jpg

5. Application of var in LINQ

In the example below we see great applications of var in LINQ queries. Only one variable var can store all values returned from the query and then use a foreach (var) to retrieve the value.

004-keyword-var-microsofttech.net.jpg

In this article we have seen a very convenient feature using the var keyword. You can apply the var keyword properly in your programs to optimize the code.

From my Site: http://microsofttech.net/lap-trinh/tu-khoa-var-trong-lap-trinh-c.html

Up Next
    Ebook Download
    View all
    Learn
    View all