Search code examples
c#string-interpolation

How to get the first char of a string by string interpolation?


static void BuildStrings(List<string> sentences)
{
    string name = "Tom";
    foreach (var sentence in sentences)
        Console.WriteLine(String.Format(sentence, name));
}
static void Main(string[] args)
{

    List<string> sentences = new List<string>();
    sentences.Add("Hallo {0}\n");
    sentences.Add("{0[0]} is the first Letter of {0}\n");

    BuildStrings(sentences);

    Console.ReadLine();
}

//Expected:
//Hallo Tom
//T is the first Letter of Tom

But I got:

System.FormatException: 'Input string was not in a correct format.'

How to get the first Letter of "Tom" without changing the BuildStrings Method?


Solution

  • You really need to do something like this:

    static void BuildStrings(List<string> sentences)
    {
        string name = "Tom";
        foreach (var sentence in sentences)
            Console.WriteLine(String.Format(sentence, name, name[0]));
    }
    
    static void Main(string[] args)
    {
        List<string> sentences = new List<string>();
        sentences.Add("Hallo {0}\n");
        sentences.Add("{1} is the first Letter of {0}\n");
    
        BuildStrings(sentences);
    
        Console.ReadLine();
    }
    

    That gives me:

    Hallo Tom
    
    T is the first Letter of Tom