I am attempting to pass objects into an Attributes constructor as follows:
[PropertyValidation(new NullOrEmptyValidatorScheme())]
public string Name { get; private set; }
With this attribute constructor:
public PropertyValidationAttribute(IValidatorScheme validator) {
this._ValidatorScheme = validator;
}
The code won't compile. How can I pass an object into an attribute as above?
EDIT: Yes NullOrEmptyValidatorScheme implements IValidatorScheme.
The error: error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.
The values into attributes are limited to simple types; for example, basic constants (including strings) and
typeof
... you can't usenew
or other more complex code. In short; you can't do this. You can give it the type though:i.e. the
PropertyValidation
ctor takes aType
, and useActivator.CreateInstance
inside the code to create the object. Note that you should ideally just store the string internally (AssemblyQualifiedName
).From ECMA 334v4:
and
As previous posters noted, the types use in attribute arguments are quite severely restricted (understandably, because their values need to be serialized directly into the assembly metadata blob).
That said, you can probably create a solution that utilizes typeofs, as those can be used.
For instance :
This syntax is perfectly legal. The code that reads your attributes you have to get the validator type, create a new instance of the validator (it can even maintain a cache of validators keyed on valicator types, if appropriate - this is a fairly common technique), and then invoke it.
Also... (I think it is a Microsoft Bug)
You can't put a default value to "null" but default simple default value are ok ('false', '7', '"Test").
NExt example will give you the following error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
in file: ... \CSC