Lets say I have the following setup.
public class User {
public string Id { get; set; }
...
}
public class Employee : User {
public string EmployeeNumber { Get; set; }
}
public class Customer : User {
public string CustomerCompany { get; set; }
}
public class AccountService {
public void Login (User user) {
//best way to access user type here while maintaining best practice
//What I'm thinking but not sure if best way and might violate SOLID
if(user is Employee)
{
var emp = (Employee)user;
//do something for employee
}
)
}
}
When I login as per comment in code is it the best way to determine the type of user?
My datastores have a Save(User user) method and when I retrieve I check the type using if check, but again not sure if right approach or a system that will grow rapidly.
Obviously other way is to have login for each type of user and avoid having to do the if check.
CodePudding user response:
The better approach would be to use a switch statement over the different possible types of the user. You can also directly cast the user into the type you're checking by placing the variable name right after the type. This works for the if and switch statement. In your case, this is what the optimal solution would look like:
public void Login(User user)
{
switch (user)
{
case Employee employee:
// do something for employee
break;
case Customer customer:
// do something for customer
break;
default:
break;
}
}
CodePudding user response:
I would suggest something like that:
private readonly Dictionary<string, Action<User>> usersLoginDispatcher = new()
{
{ typeof(Customer).Name, e => RegisterCustomer(e) },
{ typeof(Employee).Name, e => RegisterEmployee(e) },
};
...
public class AccountService {
public void Login (User user) {
usersLoginDispatcher[user.GetType().Name](user);
}
}
CodePudding user response:
you can use a switch to make the code more readable
public class AccountService
{
public void Login(User user)
{
switch (user.UserTypeName)
{
case "User":
... do something
break;
case "Employee":
var emp = user as Employee;
...do something
break;
}
}
}
and User class
public class User
{
public string Id { get; set; }
public string UserTypeName { get; private set; }
public User () {
UserTypeName=this.GetType().Name;
}
}
