Each variable in C # exists within the scope, which is determined by curly braces:
{ ... int x = 0; ... x = x + 1; // <- legal ... // <- x is defined up to here } x = x - 1; // <- illegal, providing there no other "x" declared
In your case, cust_num limited to while {...} . He should think about what value your code should return if cust_num_valid = true and there is no cust_num at all.
while (!cust_num_valid) { // <- Scope of cust_num begins cust_num_valid = true; Console.Write("Please enter customer number: "); string cust_num = Console.ReadLine(); if (cust_num == "000000" || !Regex.IsMatch(cust_num, @"^[0-9]+$") || cust_num.Length != 6) { cust_num_valid = false; Console.WriteLine("Invalid customer number detected. Customer numbers must be a 6 digit positive integer (zeros will not work)"); } } // <- Scope of cust_num ends return cust_num; // <- out of scope
To restore the code, put string cust_num = ""; outside while :
string cust_num = ""; // <- declaration while (!cust_num_valid) { cust_num_valid = true; Console.Write("Please enter customer number: "); cust_num = Console.ReadLine(); // <- no new declaration: "string" is removed if (cust_num == "000000" || !Regex.IsMatch(cust_num, @"^[0-9]+$") || cust_num.Length != 6) { cust_num_valid = false; Console.WriteLine("Invalid customer number detected. Customer numbers must be a 6 digit positive integer (zeros will not work)"); } } return cust_num;
source share