Fixing Invalid Parameter Type in Attribute Constructor

By FoxLearn 12/21/2024 2:16:37 AM   8
When attempting to pass a parameter to the constructor of 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 parameter type used in the attribute’s constructor is invalid. Although the error appears where the attribute is applied, the root cause lies in the definition of the attribute itself.

Solution – Use a Valid Parameter Type

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

  • Primitive types: int, string, bool, char, and other less common types like byte, short, long, float, and double.
  • Type: Represents a Type object.
  • Enum: Any enumeration type.
  • Arrays of the above types (e.g., int[]).

To resolve the issue, replace the invalid parameter type with one of these valid options.

Here are examples of 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) // Valid, but not the Color struct!

If the type you need to use isn't valid in an attribute constructor, you may need to convert it into a valid type. For instance, if you want to use a decimal parameter, you can pass it as a string or double and then convert it within the constructor:

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