Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 987
Adam.Er8 Avatar asked Oct 16 '25 04:10

Adam.Er8


1 Answers

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.

like image 160
Enigmativity Avatar answered Oct 17 '25 18:10

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!