Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to programming and having a problem with the following code:

    private string alphaCoords(Int32 x)
    {
        char alphaChar;

        switch (x)
        {
            case 0: alphaChar = 'A'; break;
            case 1: alphaChar = 'B'; break;
            case 2: alphaChar = 'C'; break;
            case 3: alphaChar = 'D'; break;
            case 4: alphaChar = 'E'; break;
            case 5: alphaChar = 'F'; break;
            case 6: alphaChar = 'G'; break;
            case 7: alphaChar = 'H'; break;
            case 8: alphaChar = 'I'; break;
            case 9: alphaChar = 'J'; break;
        }

        return alphaChar.ToString();
    }

The compiler says: Use of unassigned local variable 'alphaChar'

But I'm assigning it in my switch block.

I'm sure this is my fault as I dont know enough about programming.

Please advise.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
108 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're assigning it if x is 0-9. What would you expect it to do if x were 123 though? While you may know that only values between 0 and 9 will be passed in, the compiler doesn't - so it needs to consider what would happen otherwise.

One way to avoid this is to have a default case in your switch statement, which you can use to throw an exception if the value isn't in the expected range:

switch (x)
{
    case 0: alphaChar = 'A'; break;
    case 1: alphaChar = 'B'; break;
    case 2: alphaChar = 'C'; break;
    case 3: alphaChar = 'D'; break;
    case 4: alphaChar = 'E'; break;
    case 5: alphaChar = 'F'; break;
    case 6: alphaChar = 'G'; break;
    case 7: alphaChar = 'H'; break;
    case 8: alphaChar = 'I'; break;
    case 9: alphaChar = 'J'; break;
    default: throw new ArgumentOutOfRangeException();
}

Here's a slightly simpler alternative though, which removes your switch statement completely:

if (x < 0 || x > 9)
{
    throw new ArgumentOutOfRangeException();
}
char alphaChar = (char)('A' + x);

Note that you do need to exercise care when using arithmetic like this. In Java and C# the underlying representation is guaranteed to be Unicode, which makes life a lot easier. I believe it's fine for things like this (and hex parsing/formatting) but when you venture into more exotic scenarios it would fail. Then again, that's true for a lot of code simplification techniques... if they're applied inappropriately, you end up with a mess.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...