am learning C# and have written a simple bit of code, but i don’t understand why i have to declare the variables userChoice and numberR within the scope of the Main method and not within the scope of the class. If i declare it within the class like this, i get build errors
using System;
namespace FirstProgram
{
class Program
{
string userChoice;
int numbeR;
static void Main()
{
Console.WriteLine("Write a number...");
userChoice = Console.ReadLine();
numbeR = Convert.ToInt32(userChoice);
Console.WriteLine("You wrote {0}", numbeR);
Console.ReadLine();
}
}
}
But only this will give me no errors:
using System;
namespace FirstProgram
{
class Program
{
static void Main()
{
string userChoice;
int numbeR;
Console.WriteLine("Write a number...");
userChoice = Console.ReadLine();
numbeR = Convert.ToInt32(userChoice);
Console.WriteLine("You wrote {0}", numbeR);
Console.ReadLine();
}
}
}
Shouldn’t i be able to use those two variables within Main just by declaring them in the Class like above? I am confused… thanks for any advice.
You can’t do it because
Main()is a static function. Your variables are declared as instance variables and can only be accessed on an instance of theProgramclass. If you declareuserChoiceandnumbeRas static variables, it will compile.Static members mean you can use the member without instantiating the class. Imagine:
means you could do:
and all classes would have access to that change, since there is only one
MyClass.StaticIntin your program. To changeNonStaticInt, you would have to create an instance of that class, like so: