Lopsided Lopsided - 1 year ago 89
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

'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 Source

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}$";

public string Name {get; set;}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download