Compilation error using implicit array initializer as argument of C # attribute

I have a cryptic compilation error with the following test case:

[TestCase(new byte[259], new byte[] { 0, 0, 0, 0, 255 })] public void EncodeTest(byte[] source, byte[] expected) { ... } error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type 

If I replaced the first argument of the attribute as follows:

 [TestCase(new byte[259] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0, 0, 0, 255 })] public void EncodeTest(byte[] source, byte[] expected) { ... } 

It compiles just fine. Why?

Update. Let me clarify the problem. If you write the code as follows:

 int[] arr = new int[259]; Console.Write(arr[0]); // 0 

A compilation error does not occur because the compiler (or CLR?) Implicitly initializes each element with a default value.

+4
source share
1 answer

In your first construct, you simply declared an array of 259 bytes, but it is not initialized. Of course, the CLR automatically initializes the internal values ​​(in fact, it is an array, so it is not even integral, it is an object - the byte[] keyword (and the operator) - it is just syntactic sugar to make writing and reading code easier. Fact, if you wrote Array<System.Byte> someArray; someArray would be null until you initialized it, for example someArray = new Array<System.Byte>(259);

Attributes, because of error conditions, require constants (or something that can be made constant) as a parameter.

A declared array is just a declaration. Is there anything in this? You did not say that, but the compiler cannot assume that you want an array filled with zeros. You must clearly indicate what value to use. Attributes are evaluated at compile time and decorate / decorate the code construct by providing metadata (or additional functions to provide) to the various code constructs with which you used them.

0
source

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


All Articles