I'm trying to login a user by checking if the user exists in a list. I'm having trouble accessing the list and it's objects. Here is my code. Any help or hints at a solution are greatly appreciated
Thanks
public class User
{
public string userName;
public string password;
public string address;
public int contactNumber;
}
public class UserController
{
public List<User> userList;
public UserController()
{
userList = new List<User>();
}
public void RegisterUser(string username, string pass, string add, int contact)
{
User newUser = new User();
newUser.userName = username;
newUser.password = pass;
newUser.address = add;
newUser.contactNumber = contact;
userList.Add(newUser);
Console.WriteLine(newUser.userName);
Console.WriteLine(userList);
}
public void LoginUser(string username, string pass)
{
User checkUser = new User();
int idx = checkUser.userName.IndexOf(username);
if (userList[idx].password == pass)
{
Console.WriteLine("Login successful");
string[] loggedInUser = {username, pass};
}
else
{
Console.WriteLine("Incorrect password");
}
}
}
CodePudding user response:
You're instantiating a new User and checking its username property to see if it contains the username:
User checkUser = new User();
int idx = checkUser.userName.IndexOf(username);
Instead you want to check your list of users:
RegisterUser("Jeremy","Thompson","",1);
User user = userList.FirstOrDefault(u => u.userName == username);
if (user != null) {
if (user.password == password) {