views:

53

answers:

1

Hi,

For a long time I had the following bookmark in Firefox:
http://www.codeguru.com/csharp/.net/net_general/keyboard/article.php/c4639

I know decided to read it and implement it in the application it was supposed to be implemented some time ago. However, I don't see any benefit in such a method...

I know that the idea behind the hastable is provide a collection where we know for sure that there are no collisions, that every item is unique. But, is there really any big benefit in using an hashtable for keyboard accelerators?

For instance, what's the benefit in having this (as in the link above):

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    Accelerators accel = Accelerators.Unspecified;

    if (_accelHash.ContainsKey(AcceleratorKey(keyData))) {
        accel = (Accelerators)_accelHash[key];

        switch (accel) {
            case Accelerators.Home:
                DisplayHome();
                return true;
     }
    }

    return base.ProcessCmdKey(ref m, keyData); 
}

Over this:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    switch (keyData) {
     case Keys.Alt | Keys.H:
      DisplayHome();
      return true;
    }

    return base.ProcessCmdKey(ref m, keyData); 
}
+1  A: 

The first sample is configurable. You simply change the contents of the hashtable and you can change the accelerators at runtime letting the user configure them.

Here the hashtable is used not exactly for the uniqueness constraint. Its value comes from the ability to do quick retrievals of data based on a key (in this case, literally).

Are you using .NET 2.0? If so, you should use a Dictionary<Keys, Accelerator>, instead of an Hashtable, because you get strong-typing.

Martinho Fernandes
I still can't see/understand the benefit of retrieving something based on a key when I can do it directly in the case. The only reason I see for this is code organization and to make it cleaner too, nothing else. But that will only be a real benefit if I have lots of keyboard accelerators. I don't think it's worth it if they are just a few.
Nazgulled
What about the ability to change the accelerators at *runtime*?
Martinho Fernandes
I knew I was missing something, that's a good enough reason.
Nazgulled