Assigning a byte value to a char array

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; // Not OK, refused by the compiler twochars.SetValue((byte)70, 1); // OK, no exception at run-time 

Why is this operation allowed?

+4
source share
1 answer

This is because Array.SetValue() follows the CLR rules, but assignment follows C # rules for type safety.

In most cases, local variables and time series of small integer types use native int in CIL. A β€œtype” is an illusion created and forced using the C # compiler.

In the job, you have a native int in the IL operand stack, and a C # compiler that performs type checking based on the System.Byte type and C # rules for implicit conversion of integral types. The CLR is happy to write the value to an array ... the error message is added by the C # compiler. This should probably be a warning, but C # developers decided to indicate that it would be a mistake.

In Array.SetValue , you have the actual value in a box of type System.Byte and the conversion performed by the method you are calling (perhaps by delegating some other function).

+2
source

Source: https://habr.com/ru/post/1481795/


All Articles