The Array.SetValue method (Object value, int index) allows you to assign values ββto pairs of value / array pairs that are usually allowed using the general syntax of the indexer, and throws an exception when trying to combine types that are usually not allowed. For example, consider the following declaration of a local variable:
int[] twoints = new int[2] { 5, 6 };
The following four lines do not throw exceptions at runtime or compile time:
twoints[1] = (sbyte)7; twoints.SetValue((sbyte)7, 1); twoints[1] = (char)7; twoints.SetValue((char)7, 1);
On the other hand, each of these four lines throws an exception either at runtime or at design time:
twoints[1] = 4.5; twoints.SetValue(4.5, 1); twoints[1] = 4L; twoints.SetValue(4L, 1);
However, when I assign a byte value to a char array, I get strange results. The indexer syntax fails at compile time, and the SetValue API call is executed at run time:
char[] twochars = new char[2] { 'A', 'B' }; twochars[1] = (byte)70;
Why is this operation allowed?
source share