CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Also, local variables declared with the var keyword must be assigned an initial value at the exact
time of declaration and cannot be assigned the initial value of null. This last restriction should make
sense, given that the compiler cannot infer what sort of type in memory the variable would be pointing
to based only on null.
// Error! Must assign a value!
var myData;
// Error! Must assign value at exact time of declaration!
var myInt;
myInt = 0;
// Error! Can't assign null as initial value!
var myObj = null;
It is permissible, however, to assign an inferred local variable to null after its initial assignment
(provided it is a reference type).
// OK, if SportsCar is a reference type!
var myCar = new SportsCar();
myCar = null;
Furthermore, it is permissible to assign the value of an implicitly typed local variable to the value of
other variables, implicitly typed or not.
// Also OK!
var myInt = 0;
var anotherInt = myInt;
string myString = "Wake up!";
var myData = myString;
Also, it is permissible to return an implicitly typed local variable to the caller, provided the method
return type is the same underlying type as the var-defined data point.
static int GetAnInt()
{
var retVal = 9;
return retVal;
}
Implicit Typed Data Is Strongly Typed Data
Be very aware that implicit typing of local variables results in strongly typed data. Therefore, use of the
var keyword is not the same technique used with scripting languages (such as JavaScript or Perl) or the
COM Variant data type, where a variable can hold values of different types over its lifetime in a program
(often termed dynamic typing).
Note C# does allow for dynamic typing in C# using a keyword called—surprise, surprise—dynamic. You will
learn about this aspect of the language in Chapter 16.
110