How to check if a string is a valid keyword in C#?

CsharpProgrammingServer Side Programming

To check if a string is a valid keyword, use the IsValidIdentifier method.

The IsValidIdentifier method checks whether the entered value is an identifier or not. If it’s not an identifier, then it’s a keyword in C#.

Let us see an example, wherein we have set the CodeDomProvider and worked with the IsValiddentifier method −

CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");

Let us see the complete codeL

Example

 Live Demo

using System;
using System.IO;
using System.CodeDom.Compiler;

namespace Program {
   class Demo {
      static void Main(string[] args) {
   
         string str1 = "amit";
         string str2 = "for";

         CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");

         // checking for str1
         if (provider.IsValidIdentifier(str1)) {
            Console.WriteLine("{0} is an identifier", str1);
         } else {
            Console.WriteLine("{0} is a Valid Keyword in C#", str1);
         }

         // checking for str2
         if (provider.IsValidIdentifier(str2)) {
            Console.WriteLine("{0} is an identifier", str2);
         } else {
            Console.Write("{0} is a Valid Keyword in C#", str2);
         }
      }
   }
}

Output

amit is an identifier
for is a Valid Keyword in C#
raja
Published on 21-Aug-2018 12:19:49
Advertisements