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.
The compiler will just treat the constant as if you wrote the number there, but there needs to be an implicit conversion.
In your third snippet, those three
50are allSystem.Int32. Hover your mouse over it and read the tooltip in Visual Studio. Why doesn’t the compiler error here? Because the compiler knows the value at compile time and knows it will fit inside abyte.