-2

I'm trying to output a string to label in C# (Visual Studio 19), but it isn't working the way I think it works.

I haven't really tried anything else because I don't know what to do. I've searched up videos/tutorials, but none of them are helpful.

        if (Verb == 1)
        {
            Verbstring = "Getting";
        }

        lblTitle.Text = Verbstring;

I expected the label to output string "Verbstring" and "Verbstring" to change depending on what number decimal "Verb" equals. The error message says "Use of unassigned local variable 'Verbstring'.

Edit: Solved by @KenWhite

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Cloud
  • 1
  • 3
  • You've not posted enough code, but my psychic debugging skills say that you've not assigned a value to `Verbstring` in all cases. What happens when `verb` is not equal to `1`? If that doesn't help you solve the problem, then you're going to need to [edit] your post to provide a [mcve] that demonstrates the issue, because the four out-of-context lines you've posted don't do so. – Ken White Oct 11 '19 at 01:50
  • @KenWhite It generates a number from 1-4 and I've only set up an if statement for when it's equal to 1. Oh god I feel like such an idiot. I just set up if statements for those numbers and it worked. Thank you so much! – Cloud Oct 11 '19 at 01:52
  • But you've not handled any value that is not `1`, which means that it's possible for `lblTitle.Text = Verbstring` to run without a value being assigned to `Verbstring` first, which means that it could be an *unassigned local variable* at that point. – Ken White Oct 11 '19 at 01:53
  • @KenWhite Yes, you are right that worked. Thank you so much for helping me. This is my first post here, so I will make sure to post more code next time. – Cloud Oct 11 '19 at 01:55

2 Answers2

0
var Verbstring = ""; <---- the '= ""' part is important
if (Verb == 1)
{
   Verbstring = "Getting";
}
lblTitle.Text = Verbstring;

I suspect you have string Verbstring; somewhere, but in case Verb is not 1 the value of Verbstring is... uninitialised, and hence the error.

tymtam
  • 31,798
  • 8
  • 86
  • 126
0

I would change the code a little to initialise the Verbstring variable eg

 var Verbstring = "";
 if (Verb == 1)
 {
     Verbstring = "Getting";
 }

 lblTitle.Text = Verbstring;
jazb
  • 5,498
  • 6
  • 37
  • 44