views:

295

answers:

1

ThisAddIn class created with new Outlook VSTO C# project has a Application property that you can use to among other things get access to Outlook folders and items. The problem is that you can easily use it when you're inside of ThisAddIn class but there's no easy access to it from other classes in the project. This is because it's an instance property.

I want to find the best way of having access to the same functionality this property provides in my other classes so I come up with two possible solutions but I don't know which one (if any) of them is good.

Lets assume I want to get default inbox folder. Inside ThisAddIn class I would simply do something like this:

this.Application.Session.GetDefaultFolder(Outlook.olFolderInbox);

Now how to do the same outside this class?

1. Static property

First, I could add a static property to ThisAddIn class and set it to the value I want to expose in other classes.

public partial class ThisAddIn
{
    public Outlook.Application OutlookApp;

    void ThisAddIn_Startup(object sender, EventArgs e)
    {
        // init static variable value here
        OutlookApp = this.Application

        // initialize the rest of addin here
    }

    void InternalStartup()
    {
        this.Startup += this.ThisAddIn_Startup;
    }
}

This way in any of my other classes I could do something like this:

ThisAddIn.OutlookApp.Session.GetDefaultFolder(Outlook.olFolderInbox);

2. Create new Application object

Second thing that I could do is to init Application object in my other class before I use it. But I'm not sure if creating new object of that type doesn't create a new instance of Outlook.

class MyOtherClass
{
    public void MyMethod()
    {
        var app = new Outlook.Application();
        var folder = app.Session.GetDefaultFolder(Outlook.olFolderInbox);
    }
}

Does anyone have any suggestions which approach is better, of if you have different solutions for this problem I'd apprieciate that as well.

+1  A: 

Since you can have single Instance of ThisAddIn you can have a static variable to access Application form outside... FYI when you add Outlook-AddIn VSTO project,instance of ThisAddIn will be available as static member in static class Globals

Deepak N
Do I need to call it using `Globals`. If I add a static property I could call methods using `ThisAddIn.MyStaticPropertyName`.
RaYell
No..Both approaches yield the same result..
Deepak N
Apparently I can skip defining static property because I can use `Globals.ThisAddIn.Application`. Thanks for your help.
RaYell
Would this also apply to an Excel Addin?
Ahmad