10

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?

1 Answer 1

8

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...

Sign up to request clarification or add additional context in comments.

1 Comment

I can't fully explain it either, but it's to do with the way the framework invokes the constructors at run-time (they must do something with expressions or reflection that gets confused about which parameters are in the parameter array). Really, there should be a compile error about it. My approach, now that I've run into this, is to not use parameter arrays on attribute constructors at all. It's just too confusing running into this when you specify a non-default argument and then get a run-time error that gives very little indication of what's wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.