0

I'm doing a little C# program, but it is configurable. Properties.Settings.Default.foobar is equal to F3, but that is subject to change. Originally it'd be this way:

case Keys.F3:
    //dostuff
break;

But I need Properties.Settings.Default.foobar in place of F3, since it's a setting and thus subject to change.

case Keys.Properties.Settings.Default.foobar:

Obviously doesn't work, nor does putting it in parenthesis, so I'm not sure. I'm clearly new to C#, so any help?

The program uses unfocused hotkeys, but these keys are user configurable, so I can't have any sort of constant/static for a case, right?

2 Answers2

1
case Keys.Properties.Settings.Default.foobar:

As you say, this obviously doesn't work. The specific reason is that the values for a case statement must be compile-time constants.

A simpler if comparison would probably be better. Since your value is a Keys and your property is a string, you'll need to convert one type to the other for comparison. I'll convert to a string for simplicity, or you could convert the string to the enum type.

if (myVar.ToString() == Properties.Settings.Default.foobar)

So instead of having, e.g.

switch (myVar) {
    case Keys.F1:
        // something
    case Keys.F2:
        // something
}

You would have:

if (myVar.ToString() == Properties.Settings.Default.foo) {
    // something
} else if (myVar.ToString() == Properties.Settings.Default.bar) {
    // something
}
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • Could you add an example of how I would use this in this situation? –  Aug 29 '16 at 00:29
  • @coltonon I've added an example. – Tim S. Aug 29 '16 at 11:43
  • @coltonon Also, I realized I had a mistake in my code until now: You can't do `Keys.Parse` directly. Converting to enums is a little more complicated than that. I linked to a question that has answers on how you can do that conversion, if you want to go that route (and I'm sure you will at some point, if not for this particular problem). – Tim S. Aug 29 '16 at 11:52
0

Keys.F3 is a value of the Keys enumeration. So you'll need to convert your Properties.Settings.Default.foobar string into a value of the enumeration too.

Luckily, there is a built-in method to do that:

var foobarKey = (Keys)Enum.Parse(typeof(Keys), Properties.Settings.Default.foobar);
...
if (whatever == foobarKey)
{
    ...
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • This isn't working, as VS is telling me a constant is needed. The answer below seems to add more to it... –  Aug 29 '16 at 00:28
  • Ah, you'll need to use `if` instead of `case`, as the other answer mentions. Edited. – Blorgbeard Aug 29 '16 at 01:03