0

So, I want to format a string using input parameter and not the index placeholders. Preferably I would like to use a Dictionary. but I am not sure how to implement it.

var str = "I have {Bal} coins";
dictionary.Add("Bal", 20); 
var output =  

Expected Output: I have 20 coins.

I can use String format like below:

var str = "I have {0} coins";
var output = String.Format(str, 20);

My requirement is such that I need to use Dictionary.

Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • 2
    how about string interpolation using the [dollar sign](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated)? – kennyzx Sep 09 '18 at 07:58
  • 1
    Possible duplicate of [What does $ mean before a string?](https://stackoverflow.com/questions/31014869/what-does-mean-before-a-string) – D-Shih Sep 09 '18 at 08:05
  • You could maybe create a method that takes a `FormattableString` and your dictionary. The former is like an interpolated string (same syntax) but if the method accepts that type it doesn't actually format the args, but rather let's you inspect the string and the format parameters and format it yourself.. That is if `$"I have {dictionary[“bal"]} coins"` doesn't suffice – pinkfloydx33 Sep 09 '18 at 08:06
  • @pinkfloydx33: I am sorry I could not follow you. Is there any way I can use dictionary and be able to insert the values. – Unbreakable Sep 09 '18 at 08:19
  • Sure you can, even without using a 3rd party library, you can just resort to `StringBuilder.Replace` like in this example https://stackoverflow.com/questions/36759694/is-there-a-string-format-that-can-accept-named-input-parameters-instead-of-ind – ironstone13 Sep 09 '18 at 08:42
  • Do you need it to be dynamic, is the text with the placeholders provided by something other than code? – Lasse V. Karlsen Sep 25 '18 at 07:47

1 Answers1

1
var str = "I have {0} coins";
var output = String.Format(str, 20);

you can use :

var output = $"I have {variable} coins"; // variable can be dictionary or other

read this post for more : $ in C# string

AmirNorouzpour
  • 1,119
  • 1
  • 11
  • 26