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.

6
  • 2
    how about string interpolation using the dollar sign? Commented Sep 9, 2018 at 7:58
  • 1
    Possible duplicate of What does $ mean before a string? Commented Sep 9, 2018 at 8: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 Commented Sep 9, 2018 at 8: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. Commented Sep 9, 2018 at 8:19
  • Sure you can, even without using a 3rd party library, you can just resort to StringBuilder.Replace like in this example stackoverflow.com/questions/36759694/… Commented Sep 9, 2018 at 8:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.