0

I know it is generally not possible to use a non-constant value as a parameter to an attribute, but I'm wondering - if I know the value at build time, is there a way to make that a constant value in the code that I can then use as a parameter?

My situation is that I'm using an external sealed attribute class, and I need to change the parameter value depending on the environment that's being built and deployed to. Since our CI scripts do both the building and deploying, I'll know the environment name ahead of time.

I'm using dotnet3.1, and my C# version is flexible.

  • If it's available as an MSBuild property (in your csproj file), you can add an assembly-level attribute with ``, [see here](https://stackoverflow.com/questions/44501954/how-to-use-a-custom-attribute-on-an-assembly-in-net-core-1-1) – canton7 Jan 12 '22 at 14:00
  • How would I access that variable in my code if I were able to set it? – Brendan McMahon Jan 12 '22 at 15:26
  • Get a reference to your `Assembly` (e.g. through `typeof(SomeTypeInYourAssembly).Assembly`), then `.GetCustomAttribute()` – canton7 Jan 12 '22 at 16:45
  • Using `.GetCustomAttribute()` doesn't provide a constant value :-/ – Brendan McMahon Jan 12 '22 at 18:57
  • I think you're confused. The constant value was passed to that attribute by the build system -- the attribute contains the constant value. – canton7 Jan 12 '22 at 20:26
  • Oh, I know I'm confused. I've added the attribute value to the .csproj file, and I'm able to get it using the method you suggested, but if I try to use it as a parameter to the attribute, I still get the build error that it's not a constant value. – Brendan McMahon Jan 13 '22 at 13:28

0 Answers0