Attribute constructor has an invalid parameter type

By FoxLearn 3/1/2025 2:32:59 AM   65
To fix the "Attribute constructor has an invalid parameter type" error, you need to ensure that the constructor of your custom attribute is using a valid parameter type.

The .NET attribute system has specific requirements for what types can be used as constructor parameters, and using an invalid type will trigger this error.

When attempting to pass an attribute constructor parameter to a custom attribute, you may encounter 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

These errors occur because the attribute’s constructor is using an invalid parameter type. The error is shown in the line(s) where you are applying the attribute, even though the issue lies with how the attribute is defined.

Solution - Use a Valid Parameter Type

Attribute constructors can only accept types that are constant at compile time. Valid parameter types include:

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

To resolve the error, replace the invalid parameter type with one of these valid types. For example, here are constructors that use 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!

If you need to use a parameter type that isn’t valid, you can pass it in as a valid type and convert it to the desired type. For example, if you want to use a decimal in an attribute, pass it as a string (or double) and convert it:

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

By following these guidelines, you can ensure that the attribute constructor uses a valid parameter type, resolving the compiler errors.