Question Error: Use of unassigned local variable 'MyVariableName'


Oct 15, 2011
Programming Experience
(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);

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

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


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.

Last edited by a moderator:
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.

Latest posts

Top Bottom