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:
To the title-question: An explicit operator is allowed to throw (while an implicit operator should not).
But whether a null
is a valid reason to do so is a design decision, I would think not.
Consider:
object x = null;
string t = (string)x;
which does not throw.
I would use a library such as a AutoMapper to facilitate conversion between similar types. You can get greater flexibility and write less code. IMHO, using explicit cast operators is less understandable when reading code, it gives an impression that it is a cheap operation when it could be pretty complex mapping code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With