Search code examples
c#delphiunicodedelphi-7

Difference between char(x) in delphi and (char)x in C#


I have a program coded with Delphi 7 and there is this function char(x) (x is variable), and I need to write the same code in C# using (char)x, but I don't always get the same result,

So I printed all the characters x =[1..255] in Delphi 7 and C# and I found a difference in some numbers here is some examples

[![C# vs Delphi 7][1]][1]

So I want to know what is doing exactly char function of Delphi 7 so I can do the same in C#?

this is how i printed the two listes : in C#:

for (int i = 0; i < 256; i++) 
{ richTextBox1.Text = richTextBox1.Text + " I " + i.ToString() + " " + (char)(i) + Environment.NewLine; }    

In Delphi 7:

for I := 0 to 255 do begin 
  Memo5.Text := Memo5.Text +' I='+IntToStr(I)+' char(I) '+ char(I)+#13#10; 
end;

the answer was that char in Delphi uses ANSI code page and to do so in C# :

char[] characters = System.Text.Encoding.Default.GetChars(new byte[]{X});
char c = characters[0];

"System.Text.Encoding.Default.GetChars" uses ANSI code page thank you [1]: https://i.sstatic.net/yGZ8R.jpg


Solution

  • In Delphi, Char() is simply a typecast of an ordinal value to the Delphi Char type. In Delphi 7, Char is an alias to AnsiChar, which is an 8 bit character type.

    In C#, the char type is a 16 bit type, typically representing an element of UTF-16 encoded text.

    So you might translate the Delphi code to Encoding.Default.GetChars() in C#, but that is speculation at best. For instance, there is an assumption there that the ANSI locale is being used. In my view it's not possible to translate the code you have presented without more information.

    I think it is quite likely that the right way to translate your code is not to translate it literally. In other words, you need to look at the broader code to understand the complete task it performs, rather than looking line by line.