Search code examples
c#comextension-methodsoutlook-addin

Are Extension Methods on COM objects bad?


I wanted to make a .ToList() extension method for the Recipients object for Outlook, but I wasn't sure if it's good practice. Would it create an extra reference to the object that would need to be cleaned up or would it be fine as long I clean up the original Recipients object? The extension would be used something like this.

private void Foo()
{
    Recipeints recipients = mailItem.Recipients //Original recipients
    if(recipients.ToList().Intersect(listOfRecipients).Any())
    { }
    OutlookEx.ReleaseComObject(ref recipients);
}

public static class Extensions
{
    public static List<string> ToList(this Outlook.Recipients recipients)
    {
        List<string> list= new List<string>();

        if(recipients == null)
            return null;

        for (int i = 1; i <= recipients.Count; i++)
        {
            Outlook.Recipient r = recipients[i];
            list.Add(r.Name);
            OutlookEx.ReleaseComObject(ref r);
        }

        return list
    }
}

Solution

  • Extensions methods are just static methods

    Creating extensions methods do not cause an extra reference to be created, extension methods are syntactic sugar for static methods, they are still static methods but just allow you to call them in a more user-friendly way.

    var ls = Extensions.ToList(recipients)
    //is equivalent to 
    var ls = recipients.ToList()
    

    You still need to clean up your COM objects correctly

    That being said you still need to clean up and manage unmanaged resources correctly being inside of a static method, shouldn't be handled any differently than if you were implementing the method anywhere else