umpersand
umpersand

Reputation: 9

C# local variable visibility issue

I'm using an older version of Visual Studio and older framework, nonetheless the code below is very basic and should work as far as I can tell. Please don't trouble yourself with the general usefulness of it, as this is just an experiment. My question is strictly about visibility.

For some reason beyond my understanding, the compiler won't let me use myInt inside the "case (5):" block. It underlines it and says "Use of unassigned local variable 'myInt'". Shouldn't myInt be visible within the entire Foo method since it's declared right at the top? What am I missing?

    void Foo()
    {
        int myInt, x, y;
        x = 5;
        y = 0;
        for (int i = 0; i < 10; i++)
        {
            if (i == x)
            {
                myInt = i;
                break;
            }
            else
            {
                myInt = 0;
            }
        }

        if (myInt > 0)
        {
            switch (x)
            {
                case (5):
                    {
                        if (y == 0)
                        {
                            y = myInt;
                        }
                        break;
                    }
                default: { } break;
            }
        }

Upvotes: 1

Views: 102

Answers (2)

TheGeneral
TheGeneral

Reputation: 81573

It's because it's unassigned.

The compiler does static-analysis to pick up these sorts of errors. Even though intuitively it looks like you do assign it in your for loop, the compiler doesn't forward iterate the loop to prove it, there are too many degrees of freedom

Compiler Error CS0165

Use of unassigned local variable 'name'

The C# compiler doesn't allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165. For more information, see Fields. This error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not. This avoids the necessity of overly complex rules for definite assignment.

Just assign it when you create it:

int myInt = 0

Upvotes: 4

Marlon Lira
Marlon Lira

Reputation: 13

try to assign as Michael Randall is suggesting:

int myInt = 0;
int x = 5;
int y = 0;

This should correct the problem

Upvotes: 1

Related Questions