Search code examples
pythonc#string-interpolation

is there a C# equivalent for Python's self-documenting expressions in f-strings?


Since Python 3.8 it is possible to use self-documenting expressions in f-strings like this:

>>> variable=5
>>> print(f'{variable=}')
variable=5

is there an equivalent feature in C#?


Solution

  • Yes.

    int variable = 5;
    Console.WriteLine($"variable={variable}");
    

    That outputs:

    variable=5
    

    The key here is the $ that precedes the string literal.


    To do what you want with the name coming dynamically, I'd suggest a more explicit approach of using an extension method. Try this:

    public static class SelfDocExt
    {
        public static string SelfDoc<T>(
            this T value,
            [CallerArgumentExpression(nameof(value))] string name = "")
            => $"{name}={value}";
    }
    

    Then you can write this:

    int variable = 5;
    Console.WriteLine($"{variable.SelfDoc()}");
    

    It solves your problem without breaking string interpolation.