1
votes

I'm creating a VSTO addin. I want to create a dictionary once as outlook starts that I can then access from methods within the OutlookRibbon class. What is the best practice or proper method to create such a dictionary? I currently have the method where the dictionary is created in the method that uses it which is very inefficient as it's called every time. Here is the code:

public partial class OutlookRibbon
{
    private void OutlookRibbon_Load(object sender, RibbonUIEventArgs e)
    {
        genMyDict();
    }

    private void button1_Click(object sender, RibbonControlEventArgs e)
    {
        Archive();
    }
    void genMyDict()
    {
        Dictionary<string, string> myDict= new Dictionary<string, string>();
        myDict.Add("@x.com", "x");
        // many lines of this

    }

    void Archive()
    {
        if (myDict.ContainsKey("@x.com")) { // run code }
    }

Obviously this throws an error myDict does not exist in the current context in Archive()

How should I structure this so that the dictionary is only created one time but can still be accessed from my other methods within OutlookRibbon class? I can't seem to make it work. Is there a better way to create a dict for use like this in a VSTO outlook addin?

1
Shameless plug-> Check out my article C# Dictionary<T> Tricks for some cool ways to manipulate dictionaries.ΩmegaMan

1 Answers

1
votes

myDict does not exist in the current context

Change the scope of the dictionary by making it a property of the OutlookRibbon class. That will expand its scope away from the method genMyDict's localized stack.

public Dictionary<string, string> MyDictionary { get; set; }

void genMyDict()
{
    MyDictionary = new Dictionary<string, string>();
    MyDictionary.Add("@x.com", "x");
    ...
}

void Archive()
{
    if (MyDictionary.ContainsKey("@x.com")) { // run code }
}

That will allow everything to access it. For that change of the scope allows access from just one method to the whole class.