Implicitly typed variables

In C#, we generally use statically typed variables. This implies that the compiler knows the type of variable at compile time. Due to this, if it finds any operation that may result in an error, it will highlight it at compile time. For example, refer to the following code:

 int i = 1;
FileStream f = new FileStream("test.txt", FileMode.Open);
string s = i + f; // This line gives a compile error

We will observe that the compiler will give us a compile-time error. The following is the screenshot this:

As illustrated by the error description, the compiler identifies that the operation is not supported in terms of the type of the two variables, hence, it throws this error. This is referred to as explicit typing. 

Implicit typing was added to C# in version 3.0. In implicit typing, the compiler automatically identifies the variable type at compile time. The compiler does this based on the value that is assigned to the variable during declaration. The compiler then strongly types the variable to that particular type.

In C#, we use implicit typing by using the var keyword. The following shows the same code written earlier, albeit with implicit typing:

var i = 1;
FileStream f = new FileStream("test.txt", FileMode.Open);
string s = i + f; // This line gives a compile error

Please note that even though we have not implicitly specified the type of the variable as int, based upon the value 1 assigned to it, the compiler will infer that the type of the variable must be int. In this case, it will give us the same compile-time error. The following is the screenshot for this:

Implicit Type helps in the LINQ query in circumstances when the return type is determined at compile time. In addition to being a mandatory declaration, implicit typing also improves code readability. To illustrate this example, refer to the following declaration in the code.

Note that, instead of declaring the actual type, we have used the Type variable in the declaration, hence improving code readability:

Dictionary<string, IEnumerable<Tuple<Type, int>>> implicitData = new Dictionary<string, IEnumerable<Tuple<Type, int>>>();
var implicitData = new Dictionary<string, IEnumerable<Tuple<Type, int>>>();

In the next section, we will look at initializers and how they can improve code readability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.42.116