The following program will not compile:
class Program
{
static void Main(string[] args)
{
int x = 50;
Byte[] y = new Byte[3] { x, x, x };
}
}
Not surprisingly, I will get the error Cannot implicitly convert type 'int' to 'byte'
However, if I make x
a const, then it will compile:
class Program
{
public const int x = 50;
static void Main(string[] args)
{
Byte[] y = new Byte[3] { x, x, x };
}
}
I'm curious as to what's going on here. If an int
cannot be implicitly cast to a byte, does the compiler create a "byte" version of my const on the fly, or does it compile it as if I had put in an explicit cast, as it deems the constant value "safe" for a byte? Perhaps the compiler interprets this as if I had written:
Byte[] y = new Byte[3] { 50, 50, 50 };
It makes since that this is legal, I'm more curious as to what the compiler is doing here.