34

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?

2 Answers 2

33

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That's too bad, but I figured as such. Thanks.
That's too bad indeed. However, there should be such use cases, are there nice alternatives?
Does this also justify why we cannot use a static readonly String as attribute argument? Edit: Nevermind, we can use a const String.
Can we use stuff defined in appsettings.json?
4

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.

1 Comment

I briefly considered my own attribute, but I think the extra work would not justify the saved work. It's a simple problem on my end of things, but not when it has to be compiled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.