Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

c# - What is the difference between using u and x while representing character literal

I have seen u and x used interchangeably in some places while representing a character literal.

For example 'u00A9' == 'x00A9' evaluates to true

Aren't we supposed to use only u to represent unicode character? What is the use of having two ways to represent a character?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would strongly recommend only using u, as it's much less error-prone.

x consumes 1-4 characters, so long as they're hex digits - whereas u must always be followed by 4 hex digits. From the C# 5 specification, section 2.4.4.4, the grammar for x:

hexadecimal-escape-sequence:
  x hex-digit hex-digitopt hex-digitopt hex-digitopt

So for example:

string good = "Tabx9Good compiler";
string bad =  "Tabx9Bad compiler";

... look similar but are very different strings, as the latter is effectively "Tab" followed by U+9BAD followed by " compiler".

Personally I wish the C# language had never included x, but there we go.

Note that there's also U, which is always followed by 8 hex digits, primarily used for non-BMP characters.

There's one other big difference between u and x: the latter is only used in character and string literals, whereas u can also be used in identifiers:

string x = "just a normal string";
Console.WriteLine(u0078); // Still refers to the identifier x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...