Search code examples
c#string-concatenation

What does "str" + x + "str" mean?


Why would you use "str" + x + "str" in ImageLocation.

 private void CreateEnemies()
    {
        Random rnd = new Random();
        int x = rnd.Next(1, kindOfEnemies + 1);
        PictureBox enemy = new PictureBox();
        int loc = rnd.Next(0, panel1.Height - enemy.Height);
        enemy.SizeMode = PictureBoxSizeMode.StretchImage;
        enemy.ImageLocation = "Aliens/" + x + ".png";

    }

I don't understand why you would use this.


Solution

  • The + operator is used for adding. If used on a string it will not add two strings, but concatenate them:

    var text = "Hello" + "World" + "String";
    Console.WriteLine(text); // Prints "HelloWorldString"
    

    So the code above just constructs a string. Because the variable x is not of type int, .Net will automatically call .ToString().

    int x = 5;
    var text1 = "Aliens/" + x +".png"; // is the same as below.
    var text2 = "Aliens/" + x.ToString() +".png"; // is the same as above.
    
    Console.WriteLine(text); // Prints "Aliens/5.png"
    

    In C# version 6 and above you can also use string interpolation, which makes things clearer:

    var text1 = $"Aliens/{x}.png"; // is the same as below.
    var text2 = $"Aliens/{x.ToString()}.png"; // is the same as above.
    

    With string interpolation, you can embed variables into a string, by placing them into curly braces.

    Note that the string has to start with a $.