Free mag vol1 | Page 169

CHAPTER 3  CORE C# PROGRAMMING CONSTRUCTS, PART I The reason the compiler treats this code as syntactically sound is due to the fact that there is no possibility for loss of data. Given that the maximum value of a short (32,767) is well within the maximum range of an int (2,147,483,647), the compiler implicitly widens each short to an int. Formally speaking, widening is the term used to define an implicit upward cast that does not result in a loss of data.  Note Look up “Type Conversion Tables” in the .NET Framework 4.5 SDK documentation if you wish to see permissible widening (and narrowing, also see the following) conversions for each C# data type. Although this implicit widening worked in our favor for the previous example, other times this “feature” can be the source of compile-time errors. For example, assume that you have set values to numb1 and numb2 that (when added together) overflow the maximum value of a short. Also, assume you are storing the return value of the Add() method within a new local short variable, rather than directly printing the result to the console. static void Main(string[] args) { Console.WriteLine("***** Fun with type conversions *****"); // Compiler error below! short numb1 = 30000, numb2 = 30000; short answer = Add(numb1, numb2); } Console.WriteLine("{0} + {1} = {2}", numb1, numb2, answer); Console.ReadLine(); In this case, the compiler reports the following error: Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?) The problem is that although the Add() method is capable of returning an int with the value 60,000 (as this fits within the range of a System.Int32), the value cannot be stored in a short, as it overflows the bounds of this data type. Formally speaking, the CLR was unable to apply a narrowing operation. As you can guess, narrowing is the logical opposite of widening, in that a larger value is stored within a smaller data type variable. It is important to point out that all narrowing conversions result in a compiler error, even when you can reason that the narrowing conversion 6