How to determine if a string is a valid variable name?

后端 未结 5 412
执笔经年
执笔经年 2020-12-15 03:43

I\'m looking for a quick way (in C#) to determine if a string is a valid variable name. My first intuition is to whip up some regex to do it, but I\'m wondering if there\'s

5条回答
  •  一整个雨季
    2020-12-15 04:40

    In WPF this can be uses to check if a string is a valid variable name. But it does not regognize reserved strings like "public".

    // works only in WPF!
    public static bool CheckIfStringIsValidVarName(string stringToCheck)
    {
        if (string.IsNullOrWhiteSpace(stringToCheck))
            return false;
    
        TextBox textBox = new TextBox();
    
        try
        {
            // stringToCheck == ""; // !!! does NOT throw !!!
            // stringToCheck == "Name$"; // throws
            // stringToCheck == "0"; // throws
            // stringToCheck == "name with blank"; // throws
            // stringToCheck == "public"; // does NOT throw
            // stringToCheck == "ValidName";
    
            textBox.Name = stringToCheck;
        }
        catch (ArgumentException ex)
        {
            return false;
        }
    
        return true;
    }
    

提交回复
热议问题