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.
My open source library, Regextra, supports named formatting (amongst other things). It currently targets .NET 4.0+ and is available on NuGet. I also have an introductory blog post about it: Regextra: helping you reduce your (problems){2}.
The named formatting bit supports:
Example:
Result:
Check out the project's GitHub link (above) and wiki for other examples.
I doubt this will be possible. The first thing that comes to mind is how are you going to get access to local variable names?
There might be some clever way using LINQ and Lambda expressions to do this however.
Edit: What I should have said was, "No, I don't believe what you want to do is supported by C#. This is as close as you are going to get."
I solved this in a slightly different way to the existing solutions. It does the core of the named item replacement (not the reflection bit that some have done). It is extremely fast and simple... This is my solution:
It is used in the following way:
Hope someone finds this useful!
Example:
Output: 你好,wayjet,今天是2011-05-04, 这是你第18次登录,积分{ 100.40 }
I think the closest you'll get is an indexed format:
There's also String.Replace(), if you're willing to do it in multiple steps and take it on faith that you won't find your 'variables' anywhere else in the string:
Expanding this to use a List:
You could do that with a Dictionary<string, string> too by iterating it's .Keys collections, but by using a List<KeyValuePair<string, string>> we can take advantage of the List's .ForEach() method and condense it back to a one-liner:
A lambda would be even simpler, but I'm still on .Net 2.0. Also note that the .Replace() performance isn't stellar when used iteratively, since strings in .Net are immutable. Also, this requires the
MyString
variable be defined in such a way that it's accessible to the delegate, so it's not perfect yet.