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



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#
Updated on: 2020-06-22T10:08:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements