Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

named parameter type constraints

I am designing a custom attribute class.

public class MyAttr: Attribute
{
    public ValueRange ValRange { get; set; }
}

Then I am attempting to assign this attribute to a property in an adjoining class:

public class Foo
{
    [MyAttr(ValRange= new ValueRange())]
    public string Prop { get; set; }
}  

However, the compiler is complaining the following:

'ValRange' is not a valid named attribute argument because it is not a valid attribute parameter type

I also tried converting the ValueRange class to a struct in hopes that become a value type might solve the problem. Is there any way around this?

like image 220
Matthew Cox Avatar asked Apr 27 '11 19:04

Matthew Cox


1 Answers

Is there any way around this?

No.

For more details I refer you to section 17.1.3 of the C# 4 specification, which I reproduce here for your convenience:


The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
  • Single-dimensional arrays of the above types.

A constructor argument or public field which does not have one of these types, cannot be used as a positional or named parameter in an attribute specification.


Remember, the point of an attribute is to at compile time add information to the metadata associated with the entity upon which you've placed the attribute. That means that all the information associated with that attribute must have a well-defined, unambiguous way to serialize it into and out of metadata. By restricting the set of legal types to a small subset of all possible types we ensure that the compiler can always emit legal metadata that the consumer can understand.

like image 169
Eric Lippert Avatar answered Oct 09 '22 02:10

Eric Lippert