I’m writing some explicit operators to convert database model types to my domain model. Like so (simplified example):
public static explicit operator DomainModel.Role(Role roleEntity)
{
DomainModel.Role role = new DomainModel.Role
{
RoleId = roleEntity.RoleId,
Name = roleEntity.Name
};
return role;
}
However it’s possible that the roleEntity parameter is null. Most of times in the .net framework an explicit cast of a null instance results in an exception. Like so:
user.Role = (DomainModel.Role)_userRepository.GetRole(user); // Would normally results in a NullReferenceException
But if the explicit operator would be adjusted, the above would function as expected:
public static explicit operator DomainModel.Role(Role roleEntity)
{
DomainModel.Role role = roleEntity == null ? null : new DomainModel.Role
{
RoleId = roleEntity.RoleId,
Name = roleEntity.Name
};
return role;
}
Question:
- Is it logical to create such explicit operators?
To the title-question: An explicit operator is allowed to throw (while an implicit operator should not).
But whether a
nullis a valid reason to do so is a design decision, I would think not.Consider:
which does not throw.