Friday, January 30, 2015

Explicit operator

According to MSDN, explicit operator keyword declares a user-defined type conversion operator that must be invoked with a cast. This is super handy if you are doing a lot of conversion/translation in your code.

Here is an converting between two separate classes, Person and Contact - which have translatable properties between them.

  1. public class Contact {
  2. public string Name { get; set; }
  3. public string PrimaryPhone { get; set; }
  4. public string PrimaryEmail { get; set; }
  5. }
  6.  
  7. public class Person{
  8. public int PersonId { get; set; }
  9. public string FirstName { get; set; }
  10. public string LastName { get; set; }
  11. public string HomePhone { get; set; }
  12. public string HomeEmail { get; set; }
  13. public string WorkPhone { get; set; }
  14. public string WorkEmail { get; set; }
  15. public string CellPhone { get; set; }
  16. }
Then, you can create an explicit conversion operator such as this:
  1. public static explicit operator Contact (Person person)
  2. {
  3. return new Contact
  4. {
  5. Name = person.FirstName + " " + person.LastName,
  6. PrimaryPhone = (String.IsNullOrEmpty(person.CellPhone) ?
  7. (String.IsNullOrEmpty(person.WorkPhone) ?
  8. person.HomePhone : person.WorkPhone) : person.CellPhone),
  9. PrimaryEmail = (String.IsNullOrEmpty(person.WorkEmail) ? person.HomeEmail : person.WorkEmail)
  10. };
  11. }
Here is how you would use it:
  1. Contact contact = (Contact)person;

No comments: