My problem is this: I am writing a console application for c# that involves user authentication. I have declared a User class and placed all existing users in a list. I have this block to see if the user's input matches an existing username in the logon sequence.
User CurrentUser;
for (int i = 0; i < users.Count; i++)
{
if (UsernameLogonInput == users[i].Name)
{
nameExists = true;
CurrentUser = users[i];
}
}
That's all well and good, but later, I have this block, for signing in.
if (nameExists)
{
bool isValid = false;
do
{
Console.Write("Enter Password : ");
string input = Console.ReadLine();
if (input == CurrentUser.Password)
{
isValid = true;
}
else
{
Console.WriteLine("INVALID. EC102");
}
} while (!isValid);
}
The problem I'm having is that visual studio is saying "use of an unassigned local variable" to CurrentUser.Password
in the second block. I'm pretty sure this is because CurrentUser is assigned in an if statement, and I was wondering if there was any way to get around this problem of block scope.
You can easily get around the problem by initializing the variable when you declare it, even if it's a null or empty value. For example:
User CurrentUser = null;
But when you have to do this, it might indicate that there is some better way to order your logic. For example, instead of all this:
User CurrentUser;
for (int i = 0; i < users.Count; i++)
{
if (UsernameLogonInput == users[i].Name)
{
nameExists = true;
CurrentUser = users[i];
}
}
...you could just write this:
//using System.Linq;
User CurrentUser = users.SingleOrDefault( u => u.Name == UsernameLogonInput );
which will initialize the variable to either the matching user or null if none is found.
SingleOrDefault is an extension method from the System.Linq namespace. It accepts an expression as an argument, and will search the list and find any single record that matches, or default/null if there isn't a match. The argument is a lambda expression.