mardi 20 février 2018

assigning variables in if statements c#

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.

Aucun commentaire:

Enregistrer un commentaire