Question Error: Use of unassigned local variable 'MyVariableName'

webbiz

Member
Joined
Oct 15, 2011
Messages
21
Programming Experience
10+
(VS 2010)

I'm getting an error "Use of unassigned local variable 'fJDCCorrection' for the following code line:

fJDMoonPhase = fJDMoonPhase + fJDCorrection + E;

I don't understand why the error except that assignment to this variable requires making it through one of the CASE statements in my Switch.
            switch (iPhase)
            {
                case 0:
                case 2:
                    fJDCorrection = pfunPTC_NewFull(T, fMoonsArgLat, fSunsMeaAno, fMoonsMeaAno);
                    break;

                case 1:
                    fJDCorrection = pfunPTC_1stQtr(T, fMoonsArgLat, fSunsMeaAno, fMoonsMeaAno);
                    break;

                case 3:
                    fJDCorrection = pfunPTC_LastQtr(T, fMoonsArgLat, fSunsMeaAno, fMoonsMeaAno);
                    break;

            }

fJDMoonPhase = fJDMoonPhase + fJDCorrection + E;


Is it a requirement in VS C# that I assign this variable with some value initial value?

Is this VS C# way of preventing the possibility that none of the CASE statements prove true?

I'm thinking this may be the case but thought to ask as I'm really new at this.

Thanks.
 
Last edited by a moderator:

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,137
Location
Sydney, Australia
Programming Experience
10+
The issue is the fact that the, theoretically, your 'iPhase' variable may have a value other than one of those cases, e.g. 4. The compiler can't guarantee that 'fJDCorrection' will be assigned a value in all cases. You must either assign a default value to the variable before the switch statement, e.g. 0, or else add a 'default' case to your switch statement. I'd go with the latter and actually throw an exception with a documenting comment indicating that that scenario should never occur in practice. If that exception is ever thrown then you'll know there's an issue, which is definitely a good thing. With the exception thrown, the compiler will know that if execution reaches the usage of fJDCorrection then a value will have been set.

EDIT: Just thought I'd note that it would be an ArgumentOutOfRangeException.
 

annaharris

Member
Joined
May 8, 2013
Messages
13
Programming Experience
1-3
Jmcilhinney is absolutely right, it is recommended to assign some default value to the variable before the Switch statement.
 
Top Bottom