Error: Attribute constructor has an invalid parameter type

Problem

When you try to pass in an attribute constructor parameter to a custom attribute, you get one of the following compiler errors:

Error CS0181 Attribute constructor parameter has type ‘Color’ which is not a valid attribute parameter type

Error CS0655 ‘Color’ is not a valid named attribute argument because it is not a valid attribute parameter type

This error is caused by the attribute’s constructor using an invalid parameter type. The compiler shows the error on the line(s) where you’re trying to use the attribute, even though the problem is how the attribute is defined.

Solution – Use a valid parameter type

Attribute constructors can only use types that are constant at compile-time. Here are the valid parameter types:

  • int, string, bool, char (and less common: byte, short, long, float, double).
  • Type.
  • An enum.
  • Arrays of these types, such as int[].

To fix the problem, replace your invalid constructor parameter with one of these valid types. Here’s an example of constructors with valid parameter types:

public CustomAttribute(Type type)
public CustomAttribute(int i)
public CustomAttribute(string s)
public CustomAttribute(params int[] args)
public CustomAttribute(bool[] arr)
public CustomAttribute(KnownColor color) //but not the Color struct!
Code language: C# (cs)

In some cases, if the parameter type you’re using isn’t valid, you’ll need to pass in a valid type and convert it to the type you want. For example, let’s say you want to use a decimal parameter. Instead, pass it in as a string (or double) and convert it to a decimal:

public class CustomAttribute : Attribute
{
    public decimal Money { get; set; }
    public CustomAttribute(string money)
    {
        Money = Decimal.Parse(money);
    }
}
Code language: C# (cs)

Leave a Comment