I have the following situtation with overloaded constructors which I'm struggling to find a nice solution to. I can't see how to use an intermediate assignment with constructor chaining.
The following isn't valid but shows what I want to do
public MyThing(IServiceLocator services, int? userId)
{
// blah....
}
public MyThing(IServiceLocator services, string userName)
{
User user = services.UserService.GetUserByName(userName);
int userId = user == null ? null : (int?)user.Id;
// call the other constructor
this(services, userId);
}
The only way I know to write the 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 the database call twice (unless the compiler is clever enough to work that out, which I doubt).
Is there a better way to write the above?