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:
public static void AddPhoneNumber(this Contact contact, PhoneType type);
and
public static void AddPhoneNumber(this Person person, PhoneType type);
Looks cleaner to me.
If there's some common code between the two, extract that into a separate method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With