Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method in C# to check if a string is a valid identifier [duplicate]

Tags:

c#

identifier

In Java, there are methods called isJavaIdentifierStart and isJavaIdentifierPart on the Character class that may be used to tell if a string is a valid Java identifier, like so:

public boolean isJavaIdentifier(String s) {   int n = s.length();   if (n==0) return false;   if (!Character.isJavaIdentifierStart(s.charAt(0)))       return false;   for (int i = 1; i < n; i++)       if (!Character.isJavaIdentifierPart(s.charAt(i)))           return false;   return true; } 

Is there something like this for C#?

like image 876
Alex Avatar asked Dec 14 '09 23:12

Alex


People also ask

Is there methods in C?

A function is independent of any object (and outside of any class). For Java and C#, there are only methods. For C, there are only functions.

What is a method in C?

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments.

How many methods are in C?

There are two types of function in C programming: Standard library functions. User-defined functions.

Does C have a main method?

Every C program has a primary (main) function that must be named main. If your code adheres to the Unicode programming model, you can use the wide-character version of main, wmain. The main function serves as the starting point for program execution.


2 Answers

Yes:

// using System.CodeDom.Compiler; CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); if (provider.IsValidIdentifier (YOUR_VARIABLE_NAME)) {       // Valid } else {       // Not valid } 

From here: How to determine if a string is a valid variable name?

like image 119
Mark Byers Avatar answered Sep 21 '22 20:09

Mark Byers


I would be wary of the other solutions offered here. Calling CodeDomProvider.CreateProvider requires finding and parsing the Machine.Config file, as well as your app.config file. That's likely to be several times slower than the time required to just check the string your self.

Instead I would advocate you make one of the following changes:

  1. Cache the provider in a static variable.

    This will cause you to take the hit of creating it only once, but it will slow down type loading.

  2. Create the provider directly, by creating a Microsoft.CSharp.CSharpCodeProvider instance your self

    This will skip the config file parsing all together.

  3. Write the code to implement the check your self.

    If you do this, you get the greatest control over how it's implemented, which can help you optimize performance if you need to. See section 2.2.4 of the C# language spec for the complete lexical grammar for C# identifiers.

like image 29
Scott Wisniewski Avatar answered Sep 19 '22 20:09

Scott Wisniewski