Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a property to an attribute

Tags:

c#

.net

I would like to assign a property string to below attribute.

[ExtractKeyAttribute(**"Extraction"**)]

public class Extract
{
  ....
}

so extraction is my string but I don't want hard code into there. Any suggestions on better way to assign

like image 991
user1990395 Avatar asked May 01 '13 14:05

user1990395


1 Answers

You can't do this.

Attribute values must be constant expressions. The values are baked into the compiled code. If you don't want to use a constant expression, you can't use an attribute... and you possibly shouldn't. It may mean you're using attributes when you should be using a different approach.

You might want to read Eric Lippert's blog post on properties vs attributes.

Of course, you don't have to use a string literal there. You could have:

[ExtractKey(ExtractionKeys.Extraction)]
...


public static class ExtractionKeys
{
    public const string Extraction = "Extraction";
}

... but it's still a compile-time constant.

like image 111
Jon Skeet Avatar answered Oct 26 '22 23:10

Jon Skeet