Search code examples
c#stringstring-interpolation

What am I doing wrong with string interpolation in c#?


What I am doing: I am trying to build a dictionary in one function (DictionaryBuilder), extract a string from said dictionary and apply variables to it in another function (QuestionGenerator). Thus each time QuestionBuilder is called, the same string will be returned with differing contents without having to remake the same dictionary repeatedly.

        int a;
        int b;
        string theQuestion;
        string theAnswer;
        Dictionary<string, string> questionDict = new Dictionary<string, string>();

        void DictionaryBuilder()
        {
            questionDict.Add("0", $"What is {a} x {b} ?");
            questionDict.Add("1", $"The sum of {a} x {b} = {a*b}");
        }

        void QuestionGenerator()
        {
            Random rnd = new Random();
            a = rnd.Next(1, 10);
            b = rnd.Next(1, 10);
            theQuestion = questionDict["0"];
            theAnswer = questionDict["1"];
            Console.WriteLine(theQuestion);
            Console.WriteLine(theAnswer);
        }

Current results: "What is 0 x 0?" and "The sum of 0 and 0 is 0". I cannot get the new numbers to be applied.

Question: How do I make this work so I can have the creation of the dictionary and the variables separate so as that each time QuestionGenerator is called a new question of the same format is provided without needing to repeatedly rebuild the dictionary (which I assume is very inefficient)?

QuestionGenerator is called by the click of a button, so as to generate a new question in the same format.

(Please note: The actual dictionary and calculations will be far larger, more complex and the questions and answers will not be in the same dictionary - this was just for example simplicity.)


Solution

  • Create a dictionary containing your string templates

    Dictionary<string, string> questionDict = new Dictionary<string, string>();
    
    void DictionaryBuilder()
    {
        questionDict.Add("0", "What is {a} x {b} ?");
        questionDict.Add("1", "The sum of {a} x {b} = {a*b}");
    }
    

    and then use String.Format() on the retrieved string to compose your question.

    theQuestion = string.Format(questionDict["0"], a, b);