Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

525
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda