C# C# Basics Methods Variable Scope

Not Understanding Variable Scope

I'm using the code from the Variable Scope video to illustrate something I'm not understanding. According to the video, this code will not work because the variable listed in MyMethod: total isn't defined in the Main method. However, why does that matter because it is defined in MyMethod & Main points to MyMethod.

I hope that makes sense, and if I'm completely misunderstanding something, please let me know.

using System;

class Program
{
    static void MyMethod()
    {
        //this should run but according to the video it won't because Main doesn't recognize 
        // MyMethod's variables, despite them being clearly defined in MyMethod
        int total = 0;
        total += 1;
        Console.WriteLine("total in MyMethod:");
        Console.WriteLine(total);
    }

    static void Main(string[] args)
    {
        // this method runs first because it's labeled main
        myMethod();
    }
}

1 Answer

jhon white
jhon white
15,095 Points

You can call a method from your main methed, but you can't access and use the local variables of that method for example: you can't assign another value to total variable from the main method. Good luck, and keep learning!!