Anyone let me know what is going on here? Think it is something to do with the scope.

double answer;

            if (sender is System.Windows.Forms.Button)
            {
                try
                {
                    answer = Convert.ToDouble(answerBox.Text);//if cannot convert 
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Enter a valid number" + ex.Message(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
           
            setPicsToVisible();//this method sets pictures to non visible

            if (currentUser.numQuestionsComplete < 10)
            {
                checkAnswer(setValues, answer);
                currentUser.numQuestionsComplete++;
                determineShape();//get shape to be
            }

Now when the first if statement round the try catch block is removed, no errors show to me. If i keep the if statement in, i get an error that i do not assign any value to 'answer' which is annoying because i don't see how one if statement is stopping me from doing this?

Dani AI

Generated

The compiler error is coming from C# definite assignment rules: a local variable must be definitely assigned on every path before it is used. Declaring answer and only assigning it inside if (sender is System.Windows.Forms.Button) leaves a code path where answer is unassigned when later passed to checkAnswer. See the C# definite assignment rules for details ().

correctly pointed out the root cause. Fixes that avoid the compiler error (pick one that matches your intended behavior) include:

  • Initialize answer when declaring it (e.g., double answer = 0;) if a default is acceptable.
  • Move the code that uses answer inside the same if so it only runs when answer is set.
  • Use a guard clause so the method returns early when sender is not the expected button.
  • Use double.TryParse with an out variable and early return on failure (this also avoids using exceptions for flow control), as suggested. Use the overloads with NumberStyles and CultureInfo for reliable parsing (Double.TryParse).

Example pattern (different from prior posts) that uses a guard clause and TryParse:

if (!(sender is System.Windows.Forms.Button))
    return;

if (!double.TryParse(answerBox.Text,
    System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands,
    System.Globalization.CultureInfo.CurrentCulture,
    out double parsedAnswer))
{
    MessageBox.Show("Enter a valid number: " + answerBox.Text, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return;
}

double answer = parsedAnswer;

setPicsToVisible();
if (currentUser.numQuestionsComplete < 10)
{
    checkAnswer(setValues, answer);
    currentUser.numQuestionsComplete++;
    determineShape();
}

Additional notes: ex.Message is a property (not ex.Message()), avoid calling Convert.ToDouble after a successful TryParse (use the parsed value), and consider renaming setPicsToVisible() if it actually hides pictures (use a name like HidePictures() or SetPicturesVisible(bool visible) for clarity, as and observed).

Recommended Answers

All 4 Replies

You want to convert some value to double, which apparently is NOT a double. So to get rid if try, catch blocks and some strnage errors, you can use TryParse method in this manner:

double answer;
            if (sender is System.Windows.Forms.Button)
            {
                if (double.TryParse(answerBox.Text, out answer))
                    answer = Convert.ToDouble(answerBox.Text);
                else
                    MessageBox.Show("inserted value \"" + answer + "\" is not a number (type double)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

Because "answer" is only assigned a value under a condition.

If that condition is not met, you still try to use its value later.

You can avoid it by initially assigning it a value to begin with.

This line

setPicsToVisible();//this method sets pictures to non visible

gets the "Obscure Or Misnamed Method Of the Week" award.

setPicsToVisible();//this method sets pictures to non visible

I'm sorry, but that is hilarious to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.