Lopsided Lopsided - 22 days ago 8
C# Question

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.

Answer

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 RegexPatternForNameProperty = "^[a-zA-Z0-9,.# ]{1,150}$";

[RegularExpression(RegexPatternForNameProperty)]
public string Name {get; set;}