Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# I am having trouble with variables not acting as I would expect

I am trying to emulate a dice rolling and if the die lands on a certain number then it does something, and if it lands on another number it does something else. However, I am having trouble with this. Where it says if (hitPoints = 1) I am getting the error:

Cannot implicitly convert type 'int' to 'string.'

But you can clearly see that it is indeed a string. Any help on this problem would be very much appreciated, thank you in advance.

Random r = new Random();
    int hit = r.Next(1, 5);
    string hitPoints = hit.ToString();


    EmbedBuilder builder = new EmbedBuilder();



    if (hitPoints = 1)
    { 
        builder.WithTitle("");
    }
like image 688
Beef McJones Avatar asked Mar 06 '23 11:03

Beef McJones


1 Answers

Welcome to stack overflow!

I see you've declared and assigned hitpoints as a string:

string hitPoints = hit.ToString();

But below that you're comparing it (I hope) to a number:

if (hitPoints = 1)

There's two problems there. First, that's not the comparison operator. Second, the literal 1 is not a string.

If you truly want hitPoints to be a string, and you want to compare it to 1 then try this:

if (hitPoints == "1")

Side note: allow me to recommend that you don't store hitPoints as a string just to output it as one. You can always call .ToString() on your existing hit variable:

int hit = r.Next(1, 5);

if (hit == 1) {
    // do a thing
}

// using newer string interpolation, implicit hit.ToString()
Console.WriteLine($"Hit was {hit}");

// using old format, implicit hit.ToString()
Console.WriteLine("Hit was {0}", hit);

// using old format, explicit hit.ToString()
Console.WriteLine("Hit was {0}", hit.ToString());
like image 120
clarkitect Avatar answered Mar 12 '23 03:03

clarkitect