Adam_G
Adam_G

Reputation: 7879

Delegate Object Error

I am relatively new to C#, and trying to learn how to call a delegate from a Dictionary. I am using a <string, Delegate pairing. My test class is as follows:

namespace DelegatesHowTo
{
    class Program
    {
        protected delegate bool ModuleQuery(string parameter);

        static Dictionary<string, ModuleQuery> queryDictionary = new Dictionary<string, ModuleQuery>();

        public Program()
        {
            queryDictionary.Add("trustQuery", new ModuleQuery(queryTrustedStore));
            queryDictionary.Add("tokenQuery", new ModuleQuery(queryTokenStore));
        }

        static void Main(string[] args)
        {
            ModuleQuery MyQuery = new ModuleQuery(queryTrustedStore);
            queryDictionary.TryGetValue("trustQuery", out MyQuery);

            bool testQuery = MyQuery("TestTrusted");
            Console.WriteLine("Trusted: {0}", testQuery);
        }

        static bool queryTrustedStore(string parameter)
        {
            return parameter.Equals("TestTrusted");
        }

        static bool queryTokenStore(string parameter)
        {
            return parameter.Equals("TestToken");
        }
    }
}

However, the line bool testQuery = MyQuery("TestTrusted"); throws Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at DelegatesHowTo.Program.Main(String[] args) in c:\...

I was under the impression that I was instantiating an object with ModuleQuery MyQuery = new ModuleQuery(queryTrustedStore);. I guess this isn't true, though? Could someone point me in the right direction, as to how this can be corrected?

Upvotes: 0

Views: 72

Answers (1)

SLaks
SLaks

Reputation: 887469

You never ran the Program() constructor.

Therefore, the dictionary remains empty, and TryGetValue() sets the out parameter to null.

Upvotes: 7

Related Questions