views:

522

answers:

4

I can't seem to find the answer to this question.

It seems like I should be able to go from a number to a character in C# by simply doing something along the lines of (char)MyInt to duplicate the behaviour of vb's Chr() function; however, this is not the case:

In VB Script w/ an asp page, if my code says this:

Response.Write(Chr(139))

It outputs this:

‹ (character code 8249)

Opposed to this:

‹ (character code 139)

I'm missing something somewhere with the encoding, but I can't find it. What encoding is Chr() using?

+6  A: 

Chr() uses the system default encoding, I believe - so it's roughly equivalent to:

byte[] bytes = new byte[] { 139 };
char c = Encoding.Default.GetString(bytes)[0];

On my box (Windows CP1252 as the default) that does indeed give Unicode 8249.

Jon Skeet
Sure enough, that did it! Thanks!
John
+1  A: 

If you cast an int to a char, you will get the character with the Unicode character code that was in the integer. The char data type is just a 16 bit UTF-16 character code.

To get the equivalent of the VBScript chr() function in .NET you would need something like:

string s = Encoding.Default.GetString(new byte[]{ 139 });
Guffa
+1  A: 

If you want to call something that has exactly the behaviour of VB's Chr from C#, then, why not simply call it rather than trying to deduce its behaviour?

Just put a "using Microsoft.VisualBasic;" at the top of your C# program, add the VB runtime DLL to your references, and go to town.

Eric Lippert
A: 

It is funny how you ask how to do something equivalent in another language and the response is "why not just use the other language and not the one you want too" I also have the same issue and I WANT TO USE C# not VB. the whole purpose of converting is to not use the language you are converting from.....

in my case I use Convert.ToChar(8) and it returns back '\b' where VB returns a black rectangle with a white circle in it... how can i get the VB equivalent in C#?

Dale innis