Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of named identifiers in String.Format [duplicate]

Is there any way to format a string by name rather than position in C#?

In python, I can do something like this example (shamelessly stolen from here):

>>> print '%(language)s has %(#)03d quote types.' % \
      {'language': "Python", "#": 2}
Python has 002 quote types.

Is there any way to do this in C#? Say for instance:

String.Format("{some_variable}: {some_other_variable}", ...);

Being able to do this using a variable name would be nice, but a dictionary is acceptable too.

like image 803
Jason Baker Avatar asked Dec 04 '25 11:12

Jason Baker


1 Answers

This is now built-in as of C# 6 (released in 2015).

String Interpolation

var myString = $"{some_variable}: {some_other_variable}";

Previously, there was no built-in method for handling this.

Here's one method

string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);

Here's another

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

A third improved method partially based on the two above, from Phil Haack

like image 64
John Sheehan Avatar answered Dec 06 '25 00:12

John Sheehan



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!