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#?
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.
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.
There are two types of function in C programming: Standard library functions. User-defined functions.
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.
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?
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:
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.
Create the provider directly, by creating a Microsoft.CSharp.CSharpCodeProvider instance your self
This will skip the config file parsing all together.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With