Working with Variables, Operators, and Expressions in Microsoft Visual C#
- 12/15/2012
- Understanding Statements
- Using Identifiers
- Using Variables
- Working with Primitive Data Types
- Using Arithmetic Operators
- Incrementing and Decrementing Variables
- Declaring Implicitly Typed Local Variables
- Summary
- Chapter 2 Quick Reference
Declaring Implicitly Typed Local Variables
Earlier in this chapter, you saw that you declare a variable by specifying a data type and an identifier, like this:
int myInt;
It was also mentioned that you should assign a value to a variable before you attempt to use it. You can declare and initialize a variable in the same statement, like this:
int myInt = 99;
Or you can even do it like this, assuming that myOtherInt is an initialized integer variable:
int myInt = myOtherInt * 99;
Now, remember that the value you assign to a variable must be of the same type as the variable. For example, you can assign an int value only to an int variable. The C# compiler can quickly work out the type of an expression used to initialize a variable and indicate if it does not match the type of the variable. You can also ask the C# compiler to infer the type of a variable from an expression and use this type when declaring the variable by using the var keyword in place of the type, like this:
var myVariable = 99; var myOtherVariable = "Hello";
The variables myVariable and myOtherVariable are referred to as implicitly typed variables. The var keyword causes the compiler to deduce the type of the variables from the types of the expressions used to initialize them. In these examples, myVariable is an int, and myOtherVariable is a string. However, it is important for you to understand that this is a convenience for declaring variables only, and that after a variable has been declared you can assign only values of the inferred type to it—you cannot assign float, double, or string values to myVariable at a later point in your program, for example. You should also understand that you can use the var keyword only when you supply an expression to initialize a variable. The following declaration is illegal and causes a compilation error:
var yetAnotherVariable; // Error - compiler cannot infer type
If you are a purist, you are probably gritting your teeth at this point and wondering why on earth the designers of a neat language such as C# should allow a feature such as var to creep in. After all, it sounds like an excuse for extreme laziness on the part of programmers and can make it more difficult to understand what a program is doing or track down bugs (and it can even easily introduce new bugs into your code). However, trust me that var has a very valid place in C#, as you will see when you work through many of the following chapters. However, for the time being, we will stick to using explicitly typed variables except for when implicit typing becomes a necessity.