Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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!!