CustomAttributeFormatException: The binary format of the specified custom attribute is not valid

We discovered weird attribute-related behavior, and we have only one question: why? Example. First, we have some attribute with the following signature:

public class Myc : Attribute { public Myc( bool b = false, params int[] a ) { Console.WriteLine( "in ctor" ); } } 

When we try to call the constructor without parameters, the following:

 class Program { [Myc] static void Main( string[] args ) { Console.ReadKey(); } } 

We get the following exception: System.Reflection.CustomAttributeFormatException: The binary format of the specified custom attribute is not valid.

Why is this happening?

+6
source share
1 answer

Not sure what the reason is; in my own testing, this seems to be due to the combination of having one or more default parameters and the params argument in the constructor definition. However, if it holds you, there is a lazy workaround:

 public class Myc : Attribute { public Myc (params int[] a) {} public Myc( bool b, params int[] a ) { Console.WriteLine( "in ctor" ); } } 

The params argument with a value other than default, and one params argument both look fine.

Not quite an explanation, but uh ...

+6
source

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


All Articles