I have the below code which I’m using to try to apply custom attributes to fields in a declared class. I get the error below against the words ‘FileType’ and ‘AllowNulls’ in the declaration (noted below)
Error 3 ‘FieldType’ is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. F:\Dropbox\Dev_LN Projects\02 Scrap\TestFieldAttributes\TestFieldAttributes\Program.cs 61 34 TestFieldAttributes
I’ve tried various combinations of removing static, readonly etc but no luck. Any thoughts? Thanks
[AttributeUsage(AttributeTargets.Field)]
public class DBDataTypeAttribute : System.Attribute
{
private string fieldtype;
public string FieldType
{
get { return fieldtype; }
}
private string allownulls;
public string AllowNulls
{
get { return allownulls; }
}
}
public class ExpenseReport
{
[FieldQuoted('"', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
[DBDataTypeAttribute(FieldType = "varchar(1000)", AllowNulls = "true")]// errors on this line
public String UniqueID;
[FieldQuoted('"', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
public String ERNum;
}
Thanks!
Your properties are read-only, and named arguments for an attribute must be read/write, so you must add a
setmethod to the properties.If you want to use read-only properties, you should use constructor arguments for the attribute rather than named arguments.
This means you could use either this:
Or this:
Note: I used automatic properties for the latter example, but not the former, because I prefer making the fields readonly too in an attribute (readonly fields cannot be modified except in the constructor). I also changed AllowNulls to a bool since I see no reason for it to be a string.