C# parse from string to Keys

Currently I have to parse from string to Keys somehow. So basically as input I get something like "Keys.Shift" and somehow I need be able to parse this to keys so I can use it futher in the application.

I've found a solution but it doesn't work:

Keys key;
Enum.TryParse("Enter", out key);

I get a "static types cannot be used as type arguments". Does someone know a workaround or something?

Thanks in advance.

Jon Skeet
people
quotationmark

It sounds like you've got another class called Keys somewhere. Here's an example demonstrating the same problem (although there's a second error around the declaration of key which you haven't mentioned; I suspect you've got that error as well though):

using System;
using System.Windows.Forms;

static class Keys {}

class Program
{
    static void Main()
    {
        Keys key;
        Enum.TryParse("Enter", out key);
        Console.WriteLine(key);
    }
}

If you comment out the static class Keys {} the code compiles fine, which is why I suspect you've got that class somewhere - or a using directive bringing something similar in from another library.

The simplest fix is just to fully-qualify which Keys type you mean:

using System;
using System.Windows.Forms;

static class Keys {}

class Program
{
    static void Main()
    {
        System.Windows.Forms.Keys key;
        Enum.TryParse("Enter", out key);
        Console.WriteLine(key);
    }
}

people

See more on this question at Stackoverflow