and has 0 comments
Update February 2016: Tested it on Visual Studio 2015, with the Roslyn compiler, and the problem seems to have vanished.

Here is the now obsolete post:

A class in .Net can have default parameters, with values that are specified in the constructor signature, like this:
public MyClass(int p1,int p2=0) {}

If the class is inheriting from the Attribute class, then one can also specify property values when using it to decorate something, like this:
public class MyTestAttribute:Attribute {
public int P3 { get;set; }
}

[MyTest(P3=2)]
public class MyClass {}

What do you think this code would do?
public class MyTestAttribute:Attribute {
public MyTestAttribute(int p1,int p2=0) {}
public int P3 { get;set; }
}

[MyTest(1,P3=2)]
public class MyClass {}


Well, I tell you what is going to happen. Visual Studio and ReSharper both will see no problem with the syntax, but the compiler will issue an error based on the exception "error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type", but without specifying any file or line.

My guess is that it is trying to interpret the P3=2 line as an expression to be calculated and passed as the second attribute of the constructor. What I was expecting is to set the default value to the second constructor parameter, then set the property P3. The vagueness of the error points out to a possible bug.

Comments

Be the first to post a comment

Post a comment