mpen
mpen

Reputation: 282805

Default value for attribute constructor?

I'm getting this error,

error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

When I try to write something like this

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class UrlAttribute : Attribute
{
    public UrlAttribute(string pattern, string name=null)
    {
        // ...

It doesn't even show a line number, but it disappears when I take out that =null bit.

Actually, the error only occurs both when I provide a default value and rely on it (i.e., I omit it) like so

    [Url("/index")]

I'm curious to know why this? How is "null" not a constant expression?

Upvotes: 11

Views: 2488

Answers (2)

kbrimington
kbrimington

Reputation: 25642

I'm calling 'bug'.

I hope you don't mind, I reported the bug to Microsoft.

UPDATE:

I received the following feedback from Microsoft today, emphasis added.

Thanks for reporting this issue you've encountered with Visual Studio!

We've fixed up optional string parameters on attributes in our code. You'll see this fix in the version of Visual Studio after VS 2010.

Alex Turner

Program Manager

Visual Basic and C# Compiler

Upvotes: 9

siride
siride

Reputation: 209445

Attributes already provide default-able arguments. You simply create public properties on the attribute and those can be assigned in the attribute instantiation process. It already works, it's already well-understand and it's consistent with how framework attributes work. So...why not just use that mechanism instead of trying to redundantly add default parameters to the constructor?

Upvotes: 1

Related Questions