8

Refering to this link

http://msdn.microsoft.com/en-us/library/b1csw23d.aspx

it seems that it is not possible with the String.Format method to use labels instead of indices in the format string parameter.

Is there some syntax or functionality native to the .Net Framework that allows using labels instead of 0,1,...,N ?

As an example, how can this:

Console.WriteLine(String.Format("{0}{1}{0}{1}", "foo", "bar"));

become something like this:

Console.WriteLine(String.Format("{foo}{bar}{foo}{bar}", 
                                new { foo = "foo", bar = "bar" }));
  • No there isn't... Although it wouldn't be too hard to write that yourself. – Philippe Leybaert Mar 20 '12 at 11:49
  • That would be a neat way of doing it. I guess its not like that because the `Format` syntax comes from C which doesn't work like this. You could code up your own implementation with an extension method. – Oliver Mar 20 '12 at 11:51
  • possible duplicate of [Named string formatting in C#](http://stackoverflow.com/questions/159017/named-string-formatting-in-c-sharp) – Niranjan Singh Mar 20 '12 at 11:58
  • ha thanks, I hadn't found that one, the accepted answer of that question seems to be what I am looking for. –  Mar 20 '12 at 12:00

4 Answers4

4

Phil Haack wrote a blog about a way to do this:

http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx

There is no built-in way in .NET to achieve this.

Simon
  • 5,373
  • 1
  • 34
  • 46
1

As of C# 6, you can use Interpolated Strings:

string foo = "foo1";
string bar = "bar2";
Console.WriteLine($"{foo} {bar} {foo} {bar}");

Which will output:

foo1 bar2 foo1 bar2

Warr1611
  • 435
  • 8
  • 10
1

nice question after opening reflector

there isnt a way :

it counts in digits only :

enter image description here

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
1

Ref: C#: String.Inject() - Format strings by key tokens

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

it accepts an object, IDictionary or HashTable and replaces the property name/key tokens with the instance values. Since it uses string.Format internally, it uses the string.Format-like custom formatting.

.Net does not have such implementation internally. you can use Custom formatting with ICustomFormatProvider Interface.

The syntax of a format item is as follows:

{index[,length][:formatString]}
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75