Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

521
Views
Why can't I use string interpolation in an attribute?

I'm writing unit tests (MSTest) in C# 6.0 and I noticed something strange in the way the compiler handles string interpolation in attributes.

Why does this work:

[TestCategory(nameof(MyClass) + "-UnitTest")]

When this doesn't?

[TestCategory($"{nameof(MyClass)}-UnitTest")]

Ignoring the fact that this might not be a great way to categorize my tests; I'm curious why the compiler allows one and not the other.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

When the compiler encounters an interpolated string it immediately converts it into a call to String.Format so...

[TestCategory($"{nameof(MyClass)}-UnitTest")]

Becomes...

[TestCategory(string.Format("{0}-UnitTest", nameof(MyClass)))]

Attributes require that their arguments be constant expressions but the above expression will not be evaluated until execution time hence the error...

CS0182 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type...

You know all the information is available at compile time but the compiler is not smart enough to figure it out.

nameof works a bit differently than interpolated strings because it is evaluated at compile-time so there is no error.

over 4 years ago · Santiago Trujillo Report

0

Interpolated strings are not constant values. The value is determined at runtime, even though in your case all inputs can be calculated at compile time.

over 4 years ago · Santiago Trujillo Report

0

An attribute argument has to be a compile-time constant. While nameof() is a constant (see Is nameof() evaluated at compile-time?), the string interpolation feature itself is not.

An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!