简体   繁体   中英

Field is never assigned to and will always have its default value 0

I get the following error in my code and I'm not sure why:

Warning - 'SummaryForm.m_difficulty' is never assigned to, and will always have its default value 0

Code

public partial class SummaryForm : Form
{
    // Declares variables with the values pulled from the 'MainForm'
    int iCorrectACount = MainForm.iCorrectACount;
    int iCurrentQIndex = MainForm.iCurrentQIndex;

    private Difficulty m_difficulty;

    public SummaryForm()
    {

        InitializeComponent();

        double modifier = 1.0;
        if (m_difficulty == Difficulty.Easy) { modifier = 1.0; }
        if (m_difficulty == Difficulty.Medium) { modifier = 1.5; }
        if (m_difficulty == Difficulty.Hard) { modifier = 2; }

        // Sets the labels using integer values
        lblCorrectNum.Text = iCorrectACount.ToString();
        lblWrongNum.Text = (iCurrentQIndex - iCorrectACount).ToString();
        lblScoreTotal.Text = (iCorrectACount * modifier).ToString();
    }

Maybe this has something to do with why lblScoreTotal.Text will not change to the value * modifier but will on another form?

The reason I asked this question here is because someone advised me to disable warning messages but I didn't think that was the appropriate solution?

Thanks.

The compiler is entirely correct: nothing is going to change your m_difficulty field, as far as you've shown. What do you expect to set that value? Did you actually mean to set it to something based on MainForm as per iCorrectACount and iCurrentQIndex ?

How do you expect it would ever be anything other than whatever (Difficulty) 0 evaluates as?

It's pretty dodgy to be pulling initial values from a statically-accessed instance of a form, too, IMO. It would be much better if the constructor accepted initial values from whatever was constructing it.

m_difficulty is private, so it can't be accessed from outside your class, but you never assign it inside, so it will never change.

Therefore, it makes no real sense to compare it, as it will always be equal to 0.

You should always initialize a variable after you declared it.

private Difficulty m_difficulty = new Difficulty();

Something like that.

So you prevent it to be null (in this case you would get an exception).

The warning just tells you this.

It sounds to me like you're expecting m_difficulty to be bound to a dropdown selection on your user form. It is not. Even if it were, you would want to access the SelectedValue property instead of the object itself. Maybe this is what you're looking for.

Difficulty m_difficulty = (Difficulty)Enum.Parse(ddDifficulty.SelectedValue); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM