CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
myByte = myInt;
}
Console.WriteLine("Value of myByte: {0}", myByte);
Here, the value contained within the int variable (myInt) is safely within the range of a byte;
therefore, you would expect the narrowing operation to not result in a runtime error. However, given
that C# is a language built with type safety in mind, we do indeed receive a compiler error.
When you wish to inform the compiler that you are willing to deal with a possible loss of data due to
a narrowing operation, you must apply an explicit cast using the C# casting operator (). Consider the
following update to the Program type.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with type conversions *****");
short numb1 = 30000, numb2 = 30000;
// Explicitly cast the int into a short (and allow loss of data).
short answer = (short)Add(numb1, numb2);
}
Console.WriteLine("{0} + {1} = {2}",
numb1, numb2, answer);
NarrowingAttempt();
Console.ReadLine();
static int Add(int x, int y)
{
return x + y;
}
static void NarrowingAttempt()
{
byte myByte = 0;
int myInt = 200;
}
// Explicitly cast the int into a byte (no loss of data).
myByte = (byte)myInt;
Console.WriteLine("Value of myByte: {0}", myByte);
}
At this point, our code compiles; however, the result of our addition is completely incorrect:
***** Fun with type conversions *****
30000 + 30000 = -5536
Value of myByte: 200
104