C
Chris LTQ
Guest
Hi,
Currently learning how to code, and I am trying to understand how I can use the same variable accross more than one method/function but I seem to keep getting the same error :
testing.cs(14,12): error CS0165: Use of unassigned local variable 'userName'
testing.cs(28,45): error CS0103: The name 'userName' does not exist in the current context
(While I totally get that the use of multiple methods is not required for this simple task, the point is to understand HOW to do it for more complex code in the future.) The idea is the "Main" method keeps asking the user for their name, and when userName finally has a value, it calls outputUserName() to print up a line to the console, using the same "userName" variable in the output. It looks like from the error, the outputUserName(); is unable to see the "userName" variable, but i dont quite get why.
If someone could please just give me a hint WITHOUT actually posting code examples/giving the answer if possible that would be great. Just need a nudge. Thanks.
This is my code :
using System;
namespace learning
{
class Program
{
static void Main(string[] args)
{
string userName;
while (userName == "")
{
Console.WriteLine("Please enter your name : ");
userName = Console.ReadLine();
outputUserName();
}
}
public static void outputUserName()
{
Console.WriteLine("So, your name is " + userName);
}
}
}
Continue reading...
Currently learning how to code, and I am trying to understand how I can use the same variable accross more than one method/function but I seem to keep getting the same error :
testing.cs(14,12): error CS0165: Use of unassigned local variable 'userName'
testing.cs(28,45): error CS0103: The name 'userName' does not exist in the current context
(While I totally get that the use of multiple methods is not required for this simple task, the point is to understand HOW to do it for more complex code in the future.) The idea is the "Main" method keeps asking the user for their name, and when userName finally has a value, it calls outputUserName() to print up a line to the console, using the same "userName" variable in the output. It looks like from the error, the outputUserName(); is unable to see the "userName" variable, but i dont quite get why.
If someone could please just give me a hint WITHOUT actually posting code examples/giving the answer if possible that would be great. Just need a nudge. Thanks.
This is my code :
using System;
namespace learning
{
class Program
{
static void Main(string[] args)
{
string userName;
while (userName == "")
{
Console.WriteLine("Please enter your name : ");
userName = Console.ReadLine();
outputUserName();
}
}
public static void outputUserName()
{
Console.WriteLine("So, your name is " + userName);
}
}
}
Continue reading...