views:

40

answers:

2

I'm getting this error,

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?

+1  A: 
kbrimington
Don't mind at all. I get a 404 when I follow that link though. It asked me to log in, and then said the page wasn't found.
Mark
@Mark: Strange. I just tried it out and it worked just fine. Perhaps it's a permissions thing. I'll keep you posted. I did receive an automated confirmation letter indicating it was being routed to the proper team. We'll see what happens.
kbrimington
@kbrimington: It did mention permissions -- "The content that you requested cannot be found or you do not have permission to view it." So that might be it.
Mark
Huh. Interesting they gave a 404 instead of a 401, then, eh?
kbrimington
Well.. I just said "404" because it said "Page not found" \*runs off to check the headers\* It actually sent a 500.
Mark
+2  A: 

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?

siride
That wasn't the question :) But the reason "why" is because C# 4 added named parameters. With Attributes, it would seem that we now have *two* ways of defining named parameters, except that we don't, because this one raises an error; I was trying to keep the app consistent by sticking with one method. Nevertheless, I'm not saying it's a good idea to add default args, I'm just wondering *why* we can't.
Mark
It might be a bug, but I don't think it's critical because there is already a better way to do it. Sorry that C# isn't fully orthogonal.
siride