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

Time:01-26

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#?

CodePudding user response:

No, but you can use InterpolatedStringHandler and CallerArgumentExpression to write it yourself:

[InterpolatedStringHandler]
public ref struct SelfDocumentingStringHandler
{
    StringBuilder builder;

    public SelfDocumentingStringHandler(int literalLength, int formattedCount)
    {
        builder = new StringBuilder(literalLength);
    }

    public void AppendLiteral(string s)
    {
        builder.Append(s);
    }

    public void AppendFormatted<T>(T t, [CallerArgumentExpression(nameof(t))] string member = "")
    {
        builder.Append(member   "=");
        builder.Append(t);
    }

    internal string GetFormattedText() => builder.ToString();
}

void Print(ref SelfDocumentingStringHandler stringHandler)
{
    Console.WriteLine(stringHandler.GetFormattedText());
}

then you can use it like this:

var variable = 5;
Print($"{variable}"); // prints: variable=5

CodePudding user response:

Yes.

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

That outputs:

variable=5

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

CodePudding user response:

In C#, there is no direct equivalent to Python's f-strings, which allow for self-documenting expressions to be included directly in the string. However, C# does have string interpolation, which can be used to achieve a similar effect. You can use the $"{expression}" syntax to include expressions directly in the string. For example, instead of using f-string like in python f"Hello, {name}" you can use : $"Hello, {name}"

Additionally, C# also has the string.Format() method, which can be used to insert expressions into a string using placeholders. For example, instead of using f-string like in python f"Hello, {name}" you can use : string.Format("Hello, {0}", name);

Both of these C# features are similar to Python's f-strings in that they allow for expressions to be included directly in the string, making the code more readable and self-documenting.

  • Related