I have the following situation with overloaded designers with whom I am struggling to find a good solution. I don't see how to use an intermediate assignment with a chain of constructors.
The following actions are invalid, but show what I want to do
public MyThing(IServiceLocator services, int? userId)
{
}
public MyThing(IServiceLocator services, string userName)
{
User user = services.UserService.GetUserByName(userName);
int userId = user == null ? null : (int?)user.Id;
this(services, userId);
}
The only way I know to write above in valid code is
public MyThing(IServiceLocator services, string userName)
: this(services,
services.UserService.GetUserByName(userName) == null ?
null : (int?)services.UserService.GetUserByName(userName).Id)
which is not only ugly code, but also requires a double call to the database (unless the compiler is smart enough to fix it, which I doubt).
Is there a better way to write above?
source
share