How to Embed a const char in a const string in C# (and Why It Fails)
The Problem
In C#, you might occasionally need to build a compile-time constant string by combining other constants. However, trying to combine a const char with a const string results in a compiler error. Consider this code:
const char c = 'a';
const string s = "" + c; // Error CS0133: The expression being assigned to 's' must be constantEven trying string interpolation yields the same error:
const string s = $"{c}"; // Error CS0133In this article, we will look at why this happens according to the C# language specification and how you can resolve it.
Why Does This Fail? (The Spec Explanation)
According to the C# language specification (specifically the section on Constant Expressions), a constant expression is an expression that can be fully evaluated at compile-time.
While both char and string are valid constant types, the binary + operator is only defined as a constant operator for specific combinations of types. Specifically, the C# specification states that string concatenation using the + operator is a constant expression only when both operands are of type string (or null).
When you attempt to write "" + c (a string plus a char), the compiler does not have a predefined constant operator for this combination. Instead, it translates this operation into a call to a method like string.Concat(object, object) or performs an implicit conversion. Because method calls cannot be evaluated at compile-time, the expression is no longer considered constant, resulting in Error CS0133.
How to Fix It
Depending on your use case, there are several ways to achieve your goal.
Solution 1: Use static readonly instead of const
If you must keep c as a const char, the easiest workaround is to change your string from a const to a static readonly field. This evaluates the expression at runtime (during class initialization) while still preventing any modification to the string afterward:
const char c = 'a';
public static readonly string s = "" + c; // Works perfectly!Solution 2: Declare the character as a const string
If the string absolutely must be a compile-time const (for example, to use it in an attribute argument), you should change the character's type to a const string:
const string c = "a";
const string s = "" + c; // Works! Both operands are strings.Solution 3: Use String Interpolation with static readonly
If you prefer clean modern C# syntax, combining string interpolation with static readonly is highly readable:
const char c = 'a';
public static readonly string s = $"{c}";Summary
C# restricts constant string concatenation to string-only operands. By converting your character to a const string or switching your target field to static readonly, you can easily bypass this limitation while keeping your code clean and type-safe.