I’m beginning to fall in love with Extension Methods, but I just don’t know how to create an EM only for a determinate Object type.
I have for example:
public static void AddPhoneNumberToContact(this Contact contact, PhoneType type, String number) { lock (contact) { PhoneRow pr = PhoneRow.CreateNew(); pr.SetDefaults(); pr.PtypeIdx = type; pr.PhoneNumber = number; contact.Phones.Add(pr); pr = null; } }
My problem is that I want to also Have this method in the Person object, and that is why I named
AddPhoneNumberToContact AddPhoneNumberToPerson
Is there a way to have AddPhoneNumber and deal with the object that is provided?
or the solution is to have
public static void AddPhoneNumber(this object contact, ... { ... if(typeof(Contact) == contact) ((Contact)contact).Phones.Add(pr); else if(typeof(Person) == contact) ((Person)contact).Phones.Add(pr); }
Thank you.
How about writing two extension methods:
and
Looks cleaner to me.
If there’s some common code between the two, extract that into a separate method.