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?
A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value.
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.
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.
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With