// Another compiler error!
static void NarrowingAttempt()
{
byte myByte = 0;
int myInt = 200;
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 than 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 and resulting output in Figure 3-15.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with type conversions *****");
short numb1 = 30000, numb2 = 30000;
Do'stlaringiz bilan baham: |