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.

public class Contact {       
        public string Name { get; set; }
        public string PrimaryPhone { get; set; }
        public string PrimaryEmail { get; set; }
}

public class Person{
        public int PersonId { get; set; }        
        public string FirstName { get; set; } 
        public string LastName { get; set; }
        public string HomePhone { get; set; }
        public string HomeEmail { get; set; }
        public string WorkPhone { get; set; }
        public string WorkEmail { get; set; }
        public string CellPhone { get; set; }
}
Then, you can create an explicit conversion operator such as this:
public static explicit operator Contact (Person person)
{
    return new Contact 
    {
          Name = person.FirstName + " " + person.LastName,
          PrimaryPhone = (String.IsNullOrEmpty(person.CellPhone) ? 
                  (String.IsNullOrEmpty(person.WorkPhone) ? 
                  person.HomePhone : person.WorkPhone) : person.CellPhone),
          PrimaryEmail = (String.IsNullOrEmpty(person.WorkEmail) ? person.HomeEmail : person.WorkEmail)
    };
}
Here is how you would use it:
Contact contact = (Contact)person;

No comments: