Skip to content

[Discussion] Constant string interpolation #11259

@ashmind

Description

@ashmind

Problems

There are two relevant cases, and both of them are related to nameof().

  1. Consider the following code:

    public static readonly string Sql = $"SELECT {nameof(ColumnX)} ...";
    // moving to a constant
    public const string Sql = "SELECT " + nameof(ColumnX) + " ...";

    Even though nameof is a constant I have to fall back on older syntax here.

  2. Another (more insidious) example:

    var sql = new StringBuilder();
    sql.Append("SELECT * FROM " + nameof(C));
    // vs
    sql.Append($"SELECT * FROM {nameof(C)}");

    Even though approaches seem similar, the first one is a constant, while the second one does string allocation — defeating the purpose of a StringBuilder. This can be partially mitigated by having a FormattableString overload on StringBuilder, but FormattableString itself and its internal array would still need allocations.

Solution Discussion

I would like to evaluate string interpolation as a constant in certain contexts (that could only work if all values in it were constants). But I can't think of a simple syntax.

One option could be something like (const)$"A {nameof(B)} C", but I'm not too fond of it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions