Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomAttributeFormatException: Binary format of the specified custom attribute was invalid

We found some strange behavior connected with custom attributes.

Given this attribute:

public class MyAttribute : Attribute
{
    public MyAttribute(bool b = false, params int[] a)
    {
    }
}

And this usage:

class Program
{
    [MyAttribute]
    static void Main()
    {
        Console.ReadKey();
    }
}

We get the exception:

System.Reflection.CustomAttributeFormatException: Binary format of the specified custom attribute was invalid.

Why does this happen?

like image 482
bkmza Avatar asked Aug 06 '14 06:08

bkmza


Video Answer


1 Answers

Not sure exactly what the cause is; in my own testing, it seems to be related to a combination of having one or more defaulted parameters and a "params" argument in the constructor definition. However, if it's holding you up, there's a lazy workaround:

public class MyAttribute : Attribute
{
    public MyAttribute(params int[] a) : this(false) {}

    public MyAttribute(bool b, params int[] a)
    {
    }
}

A "params" argument with a non-defaulted value and a "params" argument alone both appear to be fine.

Not exactly an explanation, but eh...

like image 125
Jesse MacNett Avatar answered Sep 17 '22 03:09

Jesse MacNett