CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Rather, type inference keeps the strongly typed aspect of the C# language and affects only the
declaration of variables at compile time. After that, the data point is treated as if it were declared with
that type; assigning a value of a different type into that variable will result in a compile-time error.
static void ImplicitTypingIsStrongTyping()
{
// The compiler knows "s" is a System.String.
var s = "This variable can only hold string data!";
s = "This is fine...";
// Can invoke any member of the underlying type.
string upper = s.ToUpper();
}
// Error! Can't assign numerical data to a string!
s = 44;
Usefulness of Implicitly Typed Local Variables
Now that you have seen the syntax used to declare implicitly typed local variables, I am sure you are
wondering when to make use of this construct. First and foremost, using var to declare local variables
simply for the sake of doing so really brings little to the table. Doing so can be confusing to others
reading your code, as it becomes harder to quickly determine the underlying data type and, therefore,
more difficult to understand the overall functionality of the variable. So, if you know you need an int,
declare an int!
However, as you will see beginning in Chapter 12, the LINQ technology set makes use of query
expressions that can yield dynamically created result sets based on the format of the query itself. In these
cases, implicit typing is extremely helpful, as we do not need to explicitly define the type that a query
may return, which in some cases would be literally impossible to do. Without getting hung up on the
following LINQ example code, see if you can figure out the underlying data type of subset:
static void LinqQueryOverInts()
{
int[] numbers = { 10, 20, 30, 40, 1, 2, 3, 8 };
// LINQ query!
var subset = from i in numbers where i < 10 select i;
Console.Write("Values in subset: ");
foreach (var i in subset)
{
Console.Write("{0} ", i);
}
Console.WriteLine();
// Hmm...what type is subset?
Console.WriteLine("subset is a: {0}", subset.GetType().Name);
Console.WriteLine("subset is defined in: {0}", subset.GetType().Namespace);
}
You might be assuming that the subset data type is an array of integers. That seems to be the case,
but in fact, it is a low level LINQ data type that you would never know about unless you have been doing
111