Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables within Attributes in C#

We have some Well-Attributed DB code, like so:

[Display(Name = "Phone Number")]
public string Phone { get; set; }

Since it is quite generic we'd like to use it again, but with a different string in the Name part of the attribute. Since it's an attribute it seems to want things to be const, so we tried:

const string AddressType = "Student ";
[Display(Name = AddressType + "Phone Number")]
public string Phone { get; set; }

This seems to work alright, except that having a const string means we can't overwrite it in any base classes, thereby removing the functionality that we originally were intending to add, and exposing my question:

Is there a way to use some sort of variable inside of an attribute so that we can inherit and keep the attribute decorations?

like image 930
thepaulpage Avatar asked May 13 '10 14:05

thepaulpage


People also ask

What are the attributes of a variable in C?

Variable attributes are language extensions provided to facilitate the compilation of programs developed with the GNU C/C++ compilers. These language features allow you to use named attributes to specify special properties of data objects.

What does __ attribute __ mean in C?

The __attribute__ directive is used to decorate a code declaration in C, C++ and Objective-C programming languages. This gives the declared code additional attributes that would help the compiler incorporate optimizations or elicit useful warnings to the consumer of that code.

Can attribute be variable?

An attribute variable could be a variable that is a fixed attribute like sex, race, or gender; These variables cannot be changed or manipulated by the researcher as they are an inherent part of a person or object.

What is the relationship between attributes and variables?

Variable means the measured values can vary anywhere along a given scale. Attribute data, on the other hand, is qualitative data that have a quality characteristic or attribute that is described in terms of measurements.


2 Answers

Everything inside an attribute must be known to the compiler at compile-time. Variables are inherently variable (!) so can't be used in attributes.

If you can use a code generation tool, you'd be able to dynamically inject different (constant) values into each derived class.

like image 151
Daniel Renshaw Avatar answered Sep 29 '22 21:09

Daniel Renshaw


You could jump through hoops and use an additional attribute to define the variable portion, but that would be quite a bit of work compared to what it would produce. There's no simple way to accomplish what you're after.

like image 20
Adam Robinson Avatar answered Sep 29 '22 21:09

Adam Robinson