Sign in to follow this  
thedustbustr

dictionary of delegates c# syntax

Recommended Posts

I want to register a callback specific to a key, so i want to have a dictionary mapping keys to callbacks.
public delegate void KeyProc();
public Dictionary<Keys, KeyProc> keyprocs; 
//public Dictionary<Keys, event KeyProc> keyprocs; //Invalid token 'event' in class, struct, or interface member declaration

keyprocs.Add(Keys.PrintScreen, new KeyboardHook.KeyProc(OnPrintscreen));

if (keyprocs[key] != null)
{
    KeyProc proc = keyprocs[key];
    proc();
}

[edited: resolved one of the errors] [Edited by - thedustbustr on December 29, 2007 4:37:50 PM]

Share this post


Link to post
Share on other sites
Your test ("if keyprocs[key]") may be malformed. The indexer will throw a "key not found" exception if 'key' is not in the dictionary. If that isn't what you want, consider refactoring to

KeyProc proc;
if(keyprocs.TryGetValue(key,out proc))
proc();

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this