Erdem11
Erdem11

Reputation: 38

Encoding Char From a String

I have a string

"\u00c7"

I can convert it in code;

char chr = Convert.ToChar("\u00c7"); // value of the chr is **Ç**

but I can't convert like this

I wrore \u00c7 in textbox1

char chr2 = Convert.ToChar(textbox1.Text); //This makes an error - number of character

I'm working on it for hours and can't find any solution.

Upvotes: 1

Views: 298

Answers (1)

InBetween
InBetween

Reputation: 32760

There is no inbuilt way to do this (escape sequences are only parsed as such at compile time), but its rather easy to parse the string yourself:

static bool TryParseAsChar(this string s, out char c)
{
    if (s != null)
    {
        if (s.Length == 1)
        {
            c = s[0];
            return true;
        }

        if (s.StartsWith("\\u", StringComparison.InvariantCulture) &&
            s.Length == 6)
        {

            var hex = s.Substring(2);

            if (int.TryParse(hex,
                             NumberStyles.AllowHexSpecifier,
                             CultureInfo.InvariantCulture,
                             out var i))
            {
                c = (char)i;
                return true;
            }
        }
    }

    c = default(char);
    return false;
}

Upvotes: 2

Related Questions