Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed C# Basics!
You have completed C# Basics!
Preview
If you declare a variable within a method, it's only accessible within that method. But trust us, that's a good thing!
- Variable declared within a method is accessible only within that method
- Can declare multiple variables with same name in different scopes
using System;
class Program
{
static void MyMethod()
{
// This "total" variable is completely
// separate from the "total" variable in
// the Main method!
int total = 0;
total += 1;
Console.WriteLine("total in MyMethod:");
Console.WriteLine(total);
}
static void Main(string[] args)
{
int total = 0;
total += 10;
MyMethod();
Console.WriteLine("total in Main:");
Console.WriteLine(total);
}
}
total in MyMethod:
1
total in Main:
10
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
So here, we have a program that, within
the main method, declares a variable,
0:00
total, and then adds 10 to its value.
0:01
And you can see down in the console
that it prints that value, 10.
0:04
But what if we were to add another method
and try to access total within it?
0:07
So let's add one called
static void MyMethod.
0:11
And here, in the method body, I'm going to
attempt print the value of total again.
0:16
Console dot WriteLine, total in my method.
0:20
Console dot WriteLine total.
0:23
Let me save that, and go down to
the console and try running this.
0:25
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up