Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for attribute constructor?

Tags:

c#

attributes

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?

like image 590
mpen Avatar asked Aug 09 '10 01:08

mpen


People also ask

What is the default value of the attribute?

A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value.

What are the four default values of an attribute?

There are four different types of default values you can specify for an attribute in Default: #REQUIRED—The attribute is required. #IMPLIED—The attribute is optional. #FIXED value—The attribute has a fixed value.

What is the default value for a class object?

In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.


2 Answers

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

like image 180
kbrimington Avatar answered Sep 28 '22 06:09

kbrimington


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?

like image 32
siride Avatar answered Sep 28 '22 07:09

siride