Thursday, April 28, 2011

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

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?

From stackoverflow
  • 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);
        }
    }
    
  • You can use the Convert class. From char to ascii:

    int asciiValue = Convert.ToInt32('a');
    

    And then back from ascii value to char:

    char c = Convert.ToChar(asciiValue);
    
    Andrew Hare : Whoa - I accidentally edited your answer instead of mine!! Sorry about that!
    Razzie : Heh, it's ok. As long as it's for the better ;-)
  • For Chr() you can use:

    char chr = (char)you_char_value;
    
  • Try this...

    sum += (int) str[i];
    
  • Given char c and int i, and functions fi(int) and fc(char):

    From char to int (analog of VB Asc()): explicitly cast the char as an int: i = (int) c;

    or mplicitly cast (promote): fi(c), i+= c;

    From int to char (analog of VB Chr()):

    explicitly cast the int as an char: c = (char) i, fc( (char) i);

    An implicit cast is disallowed, as an int is wider (has a greater range of values) than a char

  • 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.

    Shaul : Except that Strings class doesn't exist inside .NET 2008... :(
    Samuel : If you add a reference, it will exist.
  • How would I do this WITHOUT using Chr() or Asc()?

    I want to use true vb.net functions only.

    Dim n As Int16

    Dim s As String = "A"

    n= Asc(s) ' n will now equal 65

    s = Chr(n) ' s will now equal "A"

0 comments:

Post a Comment