简体   繁体   中英

List C# keywords

I'm trying to find a way to list all C# keywords. I need to make a comparison, such as:

if (key == "if" || key == "while" || <further_comparisons>)
{
     // do something
}

It would be way better to do it by searching in a list of those keywords, and I would like to do it without typing them.

I'm looking at System.CodeDom namespace to see if I can find something.

If any of you could tell me where I could find it, I would really appreciate it. Thank you in advance!

You can use

using Microsoft.CSharp;

 CSharpCodeProvider cs = new CSharpCodeProvider();

then, you can use

var test = cs.IsValidIdentifier("if") //return false

You'll find a list of all keywords in the documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/index

new string[]
{
    "bool", "byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "double", "float", "decimal",
    "string", "char", "void", "object", "typeof", "sizeof", "null", "true", "false", "if", "else", "while", "for", "foreach", "do", "switch",
    "case", "default", "lock", "try", "throw", "catch", "finally", "goto", "break", "continue", "return", "public", "private", "internal",
    "protected", "static", "readonly", "sealed", "const", "fixed", "stackalloc", "volatile", "new", "override", "abstract", "virtual",
    "event", "extern", "ref", "out", "in", "is", "as", "params", "__arglist", "__makeref", "__reftype", "__refvalue", "this", "base",
    "namespace", "using", "class", "struct", "interface", "enum", "delegate", "checked", "unchecked", "unsafe", "operator", "implicit", "explicit"
};

CSharpCodeProvider has the logic to do this. But you must call it with reflection. It contains an IsKeyword function. More specifically, it has the actual list of keywords which IsKeyword uses.

private static readonly string[][] keywords

If you don't mind using reflection and a dependency on implementation details, you can use the static IsKeyWord method of the Microsoft.CSharp.CSharpCodeGenerator Class .

using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

internal class CS
    {
    private static MethodInfo methIsKeyword;
    static CS()
        {
        using (CSharpCodeProvider cs = new CSharpCodeProvider())
            {
            FieldInfo infoGenerator = cs.GetType().GetField("generator", BindingFlags.Instance | BindingFlags.NonPublic);

            object gen = infoGenerator.GetValue(cs);
            methIsKeyword = gen.GetType().GetMethod("IsKeyword", BindingFlags.Static | BindingFlags.NonPublic);
            }
        }
    public static bool IsKeyword(string input)
        {
        return Convert.ToBoolean(methIsKeyword.Invoke(null, new object[] { input.Trim() }));
        }
    }

Example usage:

bool isKeyword = CS.IsKeyword("if");

Thanks to Roslyn, you can do this with the Microsoft.CodeAnalysis.CSharp nuget package.

After adding this package, your code becomes:

using Microsoft.CodeAnalysis.CSharp;
if (SyntaxFacts.GetKeywordKind(key) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(key) != SyntaxKind.None)
{
    // do something
}

If you need this to be as fast as possible, use a static field like:

private static readonly HashSet<string> Keywords =
    SyntaxFacts.GetKeywordKinds().Select(SyntaxFacts.GetText).ToHashSet();

Then, your code becomes:

if (Keywords.Contains(key))
{
    // do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM