Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a common extension method to multiple unrelated types in a third party SDK?

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.

like image 894
balexandre Avatar asked Feb 05 '09 10:02

balexandre


1 Answers

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.

like image 93
Frederick The Fool Avatar answered Oct 23 '22 14:10

Frederick The Fool