Why does not this generate a compile error?
That's my question.
For the same reason code below does not generate an error.
ulong a = 1;
byte b;
b = Convert.ToByte(a);
There is nothing wrong with code above, in that snippet, you are stating
that you want to convert a ulong to a byte and not to trhow an error if
the conversion overflows. why would the compiler throw a compile error
here??
Like I said before, internally, the C# compiler is taking your foreach
code and creating code that the CLR can understand, **this icludes**
generating code that is doing the **convertion without trhouwing an
error**, something similar to the example avobe.
What is the reason for the compiler to accept this type of conversion.
Ah, because when you do a foreach loop internally you are calling the
GetEnumerator() function wich in turn return an IEnumerator that in turn
returns objects as it collection member, so there is no way to do a
compile time check because the compiler does not whats inside the object.
You can check the definition of the IEnumerator for more info.
If you want to loop throw an array and have the compile time check then do
a "for" loop.
ulong[] vektor = { 100000, 200000, 300000 };
for (int i = 0; i < vektor.Length; i++)
{
byte b = vektor
;
Console.WriteLine("i={0}", b);
}
//Tony
Rene said:
Your foreach loop instructions are basically translated by the C#
compiler into a bunch of other instructions that are understood by the
CLR.
One of the instructions that is emitted on your behalf is an instruction
to convert ulong to a byte without throwing an overflow error.
If you are not ok with this behavior you can change it in code by adding
the check using word:
checked
{
ulong[] vektor = { 100000, 200000, 300000 };
foreach (byte b in vektor)
{
Console.WriteLine("i={0}", b);
}
}
Hello!
Why does not this cause a compile error because a ulong has never been
implicitly convertible to byte?
ulong[] vektor = {100000,200000,300000};
foreach(byte b in vektor)
{
Console.WriteLine("i={0}", b);
}
If I have these statements below then I get a compile error.
But it's almost the same as above. Is a bug perhaps?
ulong a = 1;
byte b;
b = a; // Here a ulong is not implicitly convertible to a byte so we
get a
compile error which is correct
//Tony