Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a constant expression for use in attribute parameter?

As anyone answering this already knows, parameters of attributes require constant expressions. Optional parameters (for anything, not just attributes) also require constant expressions for their default values.

The (albeit minor) inconvenience I'm having is with RegularExpressionAttribute's pattern parameter. I have dozens of properties in my data-model that use this attribute (found in System.ComponentModel.DataAnnotations), and whenever I make a change to the validation pattern, I have to go back and make that change everryyywherrreee . . . it's really quite annoying.

My question . . .

Is there a .net structure that can be declared, recognized as a constant expression, and then be usable where constant expressions are normally required?

It would be great if I could just declare a RegexPatternForNameProperty = "^[a-zA-Z0-9,.# ]{1,150}$" property somewhere, then just change that one value as needed.

like image 329
Ross Brasseaux Avatar asked Dec 15 '22 02:12

Ross Brasseaux


1 Answers

Anything that can be defined as a const can be used in an attribute. So you are still limited to compile-time constants, but you do not have to use string or numeric values directly.

public const string RegexPatternForNameProperty = "^[a-zA-Z0-9,.# ]{1,150}$";

[RegularExpression(RegexPatternForNameProperty)]
public string Name {get; set;}
like image 86
D Stanley Avatar answered Dec 16 '22 15:12

D Stanley