Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should explicit operators return null in c#?

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?
like image 408
Herman Cordes Avatar asked Aug 02 '11 10:08

Herman Cordes


2 Answers

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.

like image 112
Henk Holterman Avatar answered Oct 05 '22 04:10

Henk Holterman


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.

like image 39
Vasea Avatar answered Oct 05 '22 04:10

Vasea