Is there a C# equivalent of Pythons chr and ord?
In C#, char
is efficiently UInt16
; that's why we can simply cast:
chr: (char)
explicit cast (if i
is out of [0..UInt16.MaxValue]
range we'll have integer overflow)
int i = ...
char c = (char) i;
ord: either (int)
or even implicit cast (cast from char
to int
is always possible)
char c = ...
int i = c;
In Python 3, the strings work in terms of Unicode code points, whereas in C# the char
is a UTF-16 code unit so if you cast between int
and char
you won't be able to handle characters outside the Basic Multilingual Plane.
If handling non-BMP code points matters to you, the equivalent of chr
would be char.ConvertFromUtf32(int)
- this returns a string
as non-BMP characters will end up being represented as two UTF-16 code units.
The equivalent of ord
would be char.ConvertToUtf32(string, int)
which would allow you to find the code point at the given index in a string, taking account of whether or not it is made up of two UTF-16 code units. In contrast, if you have a char
then the best you can do is a cast.