1

At more and more places all over my code, I am using KeyValuePair<string,string> and Dictionary<string,string> in the following way: The KeyValuePair contains primary eMail and UPN name, and I always fail to memorize which one is in Key and which one is in Value.

Can I "derive" classes from KVP/Dict in such a way that I only rename Key and Value (to UPN and eMail, respectively), but keep all their inner workings?

If not, which other easy-to-maintain possibilities do I have to help me memorizing which one is which?

Alexander
  • 19,906
  • 19
  • 75
  • 162

1 Answers1

4

An easy solution is to use the built-in .NET MailAddress class from System.Net.Mail for your eMail instead of a string. This also adds the bonus that your address gets validated as well.

edit: link to the MSDN file.

http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress(v=vs.110).aspx

Nzall
  • 3,439
  • 5
  • 29
  • 59
  • If I'd use that MailAddress for every email address in my code, I guess that this will also help to avoid problems with comparison of UPPERCASE, lowercase, CamelCase email adresses? – Alexander Sep 17 '14 at 10:19
  • Just to note for future reference: I will still have to use a custom comparator. `mail1.Equals(mail2)` is true iff the mail adress is the same (case invariant) and the display name is the same (case invariant). Same mail address (case invariant) alone does not suffice, and `mail1.Address==mail2.Address` is true iff mail adress is truly the same (case sensitive). – Alexander Sep 17 '14 at 10:32
  • @Alexander You should be saving lowercase email addresses anyway, since every mailserver or mail client that uses them does this as well. Uppercase and Lowercase doesn't matter for an emailaddress to send, because they're only sent in lowercase. – Nzall Sep 17 '14 at 10:59
  • Exchange Mail Server does not save mail adresses in lowercase. I am comparing email adresses from SQL (I store them lowercase) to email adresses from AD (which will be whichever casing the admin chose when creating the Exchange account). – Alexander Sep 17 '14 at 11:07
  • Still, you should always be comparing them in lowercase. There are certain lowercase letters that get mangled when bringing them to uppercase, like that German `ß` (although I'm not sure if email addresses support Sharp S). – Nzall Sep 17 '14 at 11:19
  • I am already "always comparing them in lowercase" - at least I hope so. But one can never be sure until the first bug report comes in. So having a special datatype for email adresses, which brings along its own comparator, is very useful and I don't know why I didn't think of this earlier. So, right now I'm going through the pain of converting every string containing an smtpAdress to a custom MailAddress data type. Once I'm finished, my code will look better, and be less error-prone. – Alexander Sep 17 '14 at 11:30