Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of VB's Asc() and Chr() functions in C#?

Tags:

c#

vb.net

ascii

VB has a couple of native functions for converting a char to an ASCII value and vice versa - Asc() and Chr().

Now I need to get the equivalent functionality in C#. What's the best way?

like image 622
Shaul Behr Avatar asked Apr 06 '09 12:04

Shaul Behr


2 Answers

You could always add a reference to Microsoft.VisualBasic and then use the exact same methods: Strings.Chr and Strings.Asc.

That's the easiest way to get the exact same functionality.

like image 102
Garry Shutler Avatar answered Oct 11 '22 12:10

Garry Shutler


For Asc() you can cast the char to an int like this:

int i = (int)your_char; 

and for Chr() you can cast back to a char from an int like this:

char c = (char)your_int; 

Here is a small program that demonstrates the entire thing:

using System;  class Program {     static void Main()     {         char c = 'A';         int i = 65;          // both print "True"         Console.WriteLine(i == (int)c);         Console.WriteLine(c == (char)i);     } } 
like image 28
Andrew Hare Avatar answered Oct 11 '22 13:10

Andrew Hare