-3

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.

Iqon
  • 1,920
  • 12
  • 20
Rakibul Islam
  • 954
  • 1
  • 14
  • 25
  • 1
    It inserts a (random) number x into the path, so it effectively loads a random image.. – TaW Jul 24 '17 at 16:53
  • 1
    You don't understand the syntax or the motivation behind using a random number to build an image path? – Claudio Redi Jul 24 '17 at 16:54
  • @Md Rakibul Islam If one of the answers solved your problem, please mark it as resolved to close this thread. If not please clarify what is still missing. – Iqon Jul 25 '17 at 06:15

4 Answers4

2

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 $.

Iqon
  • 1,920
  • 12
  • 20
0

+ is used for string concatenation

wdc
  • 2,623
  • 1
  • 28
  • 41
0

It is concatenating strings together. So "Aliens/" + The string value of 'x' + ".png" are being 'added' together.

Lets say:

int x = 1

The output string would be

"Aliens/1.png"
Wyatt Shuler
  • 334
  • 2
  • 12
0

This is a way to randomize the image of the alien that you get.

Your solution has a folder called Aliens with files named 0.png, 1.png, 2.png, and so on in it. Each file has an image of an "alien", which your program loads into a PictureBox. Your code picks one of these files at random, using string concatenation.

With C# 6 and newer you can use string interpolation:

enemy.ImageLocation = $"Aliens/{x}.png";
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523