Start Debugging

Fix CS0133: The expression being assigned must be constant, when putting a const char in a const string in C#

"" + c and $"{c}" are never constant for a const char c, because string + char binds to string + object and boxes. Make the string the source of truth and match chars with list patterns or a span.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

You cannot build a const string out of a const char in C#, not with "" + c, not with $"{c}", and not with c.ToString(). string + char binds to the predefined string operator +(string, object), which boxes the char, and boxing is not allowed in a constant expression; constant interpolated strings only accept holes of type string. The fix is to flip the source of truth: declare the const string and get at its character without needing a const char, by matching strings with a list pattern (token is [Comma]) and matching chars against string constants through a one-element ReadOnlySpan<char>. Everything below was compiled and run on .NET SDK 11.0.100 (C# 15, Roslyn 5.12) with runtime 11.0.0 on macOS arm64; the rules have not changed since C# 10.

The error in context

This is the case from a Stack Overflow question with a score of 9: someone has a const char and wants a const string that contains it, so string-based switch expressions and char-based ones can share one set of constants.

Program.cs(3,19): error CS0133: The expression being assigned to 's1' must be constant
Program.cs(4,19): error CS0133: The expression being assigned to 's2' must be constant

The same root cause surfaces under different codes depending on where the constant is required. All three of these were produced by SDK 11.0.100 from the same const char c = ',':

error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
error CS1736: Default parameter value for 'sep' must be a compile-time constant
error CS9135: A constant value of type 'string' is expected

CS0182 comes from [Obsolete("separator is " + c)], CS1736 from string sep = "" + c as an optional parameter, and CS9135 from "" + c used as a case arm in a switch expression.

Minimal repro

// .NET 11 (SDK 11.0.100), C# 15
const char c = 'a';
const string s1 = "" + c;          // CS0133
const string s2 = $"{c}";          // CS0133
const string s3 = "x" + 'a';       // CS0133, even with a char literal
const int n = 1;
const string s4 = "x" + n;         // CS0133, same problem with int
const string s5 = "x" + "y";       // OK
const string s6 = $"{s5}z";        // OK, constant interpolated string (C# 10+)
const string s7 = nameof(c);       // OK, but that is the name "c", not 'a'
const char c2 = "a"[0];            // CS0133, indexing is not constant either
const string s8 = c.ToString();    // CS0133, method calls are never constant
const string s9 = (string)c;       // CS0030: Cannot convert type 'char' to 'string'

Build it with dotnet build and every commented line fails with the code shown. Note s3: the problem is not that c is a local constant, a char literal fails the same way. And c2 shows the trap also works in reverse: you cannot derive a const char from a const string.

Why "" + c is not a constant expression

The C# spec’s constant expressions section (12.26) lists char and string as constant types and permits the predefined binary + operator, which is why the question’s author expected this to work. The detail that decides it is the list of conversions allowed inside a constant expression: identity, numeric, enumeration, constant expression conversions, and reference conversions of a null constant. Boxing is explicitly excluded.

There is no string operator +(string, char) in C#. The predefined string concatenation operators are string + string, string + object and object + string. So "" + c binds to string + object, and getting c into that object parameter is a boxing conversion. You can ask the compiler that ships with SDK 11.0.100 directly. This program loads Microsoft.CodeAnalysis.CSharp.dll from the SDK’s Roslyn/bincore folder and inspects the bound operators:

// .NET 11 (SDK 11.0.100), references the SDK's own Roslyn 5.12 assemblies
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

var code = """
class C {
  const char c = 'a';
  const string s0 = "x" + "y";
  static string s1 = "" + c;
  static string s2 = $"{c}";
}
""";
var tree = CSharpSyntaxTree.ParseText(code);
var refs = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
    .Split(Path.PathSeparator).Select(p => MetadataReference.CreateFromFile(p));
var comp = CSharpCompilation.Create("x", [tree], refs,
    new(OutputKind.DynamicallyLinkedLibrary));
var model = comp.GetSemanticModel(tree);

foreach (var b in tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>())
    Console.WriteLine($"{b}: operator {model.GetSymbolInfo(b).Symbol?.ToDisplayString()}; " +
        $"right operand converted to {model.GetTypeInfo(b.Right).ConvertedType}, " +
        $"boxing = {model.GetConversion(b.Right).IsBoxing}; " +
        $"constant = {model.GetConstantValue(b).HasValue}");

foreach (var i in tree.GetRoot().DescendantNodes().OfType<InterpolatedStringExpressionSyntax>())
    Console.WriteLine($"{i}: constant = {model.GetConstantValue(i).HasValue}");

Output:

"x" + "y": operator string.operator +(string, string); right operand converted to string, boxing = False; constant = True
"" + c: operator string.operator +(string, object); right operand converted to object, boxing = True; constant = False
$"{c}": constant = False

That is the whole answer to “which part of the standard am I violating”: the operator is predefined, but its right operand is object, and the char gets there by boxing. Outside a constant context that binding is harmless: the compiler lowers the expression to a c.ToString() call (plus a concatenation where needed), which is why the non-const version compiles fine and allocates a new string.

Interpolated strings follow a separate, stricter rule. Section 12.8.3 of the spec, which absorbed the C# 10 “constant interpolated strings” feature, says an interpolated string is constant only if every interpolation is a non-null constant expression of type string, with no alignment or format specifier. {c} has type char, so $"{c}" is out, and so is $"{123}". There is no C# 15 change here.

Fix 1: make the string the source of truth

The question’s real goal (spelled out in its comments) is not to concatenate characters for its own sake: it has switch expressions on strings, which need const string arms, and switch expressions on chars, which need const char arms, and it does not want to declare every separator twice. Since a const string can be composed from other const string values but a const char can never come from anything except a char literal, put the string first and remove the need for the char constant.

// .NET 11 (SDK 11.0.100), C# 15
static class Tokens
{
    public const string Comma = ",";
    public const string Arrow = "->";
    public const string Header = $"{Comma}{Arrow}"; // constant: every hole is a const string

    // char input, string constants: view the char as a one-element span
    public static string ClassifyChar(char c) => new ReadOnlySpan<char>(in c) switch
    {
        Comma => "comma",
        _ => "other",
    };
}

Two language features make this work:

  • Since C# 11, an expression of type Span<char> or ReadOnlySpan<char> can be matched against a constant string pattern, as the patterns reference documents. The match compares the characters, so a one-element span matches the one-character constant ",".
  • new ReadOnlySpan<char>(in c) uses the single-element ReadOnlySpan<T> constructor (added in .NET 7, declared with a ref readonly T parameter since .NET 8) to wrap the local without copying or allocating. The ref readonly parameter accepts in at the call site. It needs a variable to point at, so copy a field into a local first, as the benchmark below does.

Header prints ,->. That composite constant is exactly what the char-first design could never give you.

Fix 2: keep the char, match strings with a list pattern

If the char constants are the ones you want to keep (for example, they feed an attribute whose parameter is char, or a hot tokenizer that switches on char), the string side does not need its own const string at all. Strings are countable and indexable, so C# 11 list patterns work on them, and a list pattern’s elements can be const char values:

// .NET 11 (SDK 11.0.100), C# 15
static class Tokens
{
    public const char CommaChar = ',';
    public const string Arrow = "->";

    public static string Classify(string token) => token switch
    {
        [CommaChar] => "comma",   // a string of length 1 whose only char is ','
        Arrow => "arrow",
        _ => "other",
    };
}

Console.WriteLine(Tokens.Classify(","));   // comma
Console.WriteLine(Tokens.Classify("->"));  // arrow
Console.WriteLine(Tokens.Classify("x"));   // other
Console.WriteLine("->" is ['-', '>']);     // True

[CommaChar] checks Length == 1 and then token[0] == ','. List patterns and constant string patterns mix freely in the same switch, so multi-character tokens stay as ordinary const string arms. This is the cleanest answer to the original question: one const char, zero duplicated string constants.

What the workarounds cost

The accepted answer on the question benchmarked a few of these shapes on .NET 10. Here is a rerun on .NET 11 with BenchmarkDotNet 0.15.8, four arms per switch, matching the last arm ('d' / "d"). It ran with --inProcess because BenchmarkDotNet 0.15.8 does not recognise the .NET 11 runtime for its out-of-process toolchain.

// .NET 11.0.0, BenchmarkDotNet 0.15.8, run with: dotnet run -c Release -- bench --inProcess --filter '*'
[MemoryDiagnoser]
public class Match
{
    const char A = 'a', B = 'b', C = 'c', D = 'd';
    const string SA = "a", SB = "b", SC = "c", SD = "d";
    char _c = 'd';
    string _s = "d";

    [Benchmark(Baseline = true)] public int CharSwitch() => _c switch { A => 1, B => 2, C => 3, D => 4, _ => 0 };
    [Benchmark] public int SpanSwitch() { char c = _c; return new ReadOnlySpan<char>(in c) switch { SA => 1, SB => 2, SC => 3, SD => 4, _ => 0 }; }
    [Benchmark] public int ToStringSwitch() => _c.ToString() switch { SA => 1, SB => 2, SC => 3, SD => 4, _ => 0 };
    [Benchmark] public int StringSwitch() => _s switch { SA => 1, SB => 2, SC => 3, SD => 4, _ => 0 };
    [Benchmark] public int ListPatternSwitch() => _s switch { [A] => 1, [B] => 2, [C] => 3, [D] => 4, _ => 0 };
}
BenchmarkDotNet v0.15.8, Apple M4, .NET SDK 11.0.100
Runtime=.NET 11.0.0 (11.0.0, 11.0.26.53018), Arm64 RyuJIT armv8.0-a

| Method            | Mean      | Allocated |
|------------------ |----------:|----------:|
| CharSwitch        | 0.0000 ns |         - |
| SpanSwitch        | 0.0000 ns |         - |
| ToStringSwitch    | 2.2997 ns |      24 B |
| StringSwitch      | 0.9871 ns |         - |
| ListPatternSwitch | 0.0000 ns |         - |

A 0 ns mean means the method is below BenchmarkDotNet’s measurement resolution, not literally free: the char switch, the span switch and the list pattern all compile down to a handful of compare-and-branch instructions. The one shape worth avoiding in a hot path is c.ToString(), which allocates a new 24-byte string on every call. A separate check with GC.GetAllocatedBytesForCurrentThread() on .NET 11.0.0 showed two consecutive ToString() calls on 'a', ',', 'é' and '中' each allocate 48 bytes and return different instances, so there is no single-character string cache to rely on.

Fix 3: if you must keep both constants, guard them

Sometimes both really are needed: a char attribute parameter on one side, a composite const string on the other. Then declare both, keep them next to each other, and let a test fail when they drift. There is no compile-time check available: "," and ',' cannot be compared in a constant expression (that would need the same boxing), and pattern matching a constant against a constant produced no warning on SDK 11.0.100 even when the values disagreed.

// .NET 11 (SDK 11.0.100), C# 15, xUnit or any test framework
public static class Sep
{
    public const char CommaChar = ',';
    public const string Comma = ",";
}

[Fact]
public void Char_and_string_constants_agree() =>
    Assert.True(Sep.Comma is [Sep.CommaChar]);

If the string does not need to be a constant (no attribute, switch arm, optional parameter or const composite consumes it), the simplest fix of all is static readonly string Comma = CommaChar.ToString();. It is computed once, never drifts, and costs nothing after type initialisation. It just cannot appear anywhere the compiler demands a constant, which is the whole reason CS0133, CS0182, CS1736 and CS9135 exist.

Gotchas and lookalikes

  • nameof is not a workaround. const string s = nameof(c) compiles, but yields "c", the identifier, not the character it holds.
  • Escape sequences are still literals. const string Tab = "\t" and const char TabChar = '\t' are two declarations of the same value; nothing ties them together, so they need the guard from Fix 3.
  • Numbers hit the same wall. const string s = "v" + 2; fails for the same reason: string + object and boxing. Constant interpolated strings do not help either, since $"{2}" has an int hole. Write "v2", or declare the number as a const string too.
  • Format specifiers break constant interpolation. $"{Comma,5}" or $"{Comma:x}" is never constant, even when Comma is a const string.
  • CA2254 is a separate rule. If you landed here because a logging analyzer wants a constant message template, the rule and its workarounds are covered in reusing a structured log message without violating CA2254.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.