I have the following code -
using System;
namespace MyApp {
class Program {
static void Main() {
byte x = 10, y = 20;
Console.WriteLine(x.GetType());
Console.WriteLine(y.GetType());
//byte z = (x+y); Error: (9,14): error CS0266:
//Cannot implicitly convert type 'int' to 'byte'.
//An explicit conversion exists (are you missing a cast?)
byte z = (byte)(x+y);
Console.WriteLine(z.GetType());
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}
}
Output:
System.Byte
System.Byte
System.Byte
10
20
30
But instead of explicit type casting if byte z = x+y is used it generates the error -
(9,14): error CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
But as shown in the code, compiler reads x and y as byte.
So, why addition of two bytes is generating int requiring explicit type casting?