Home » Sharepoint

Equivalent in C# of Asc & Chr functions of VB

Although the subject of this post indicates it's a very simple problem but I'm having tough time in finding a solution.

I'm having some old VB code which is using these functions to get ASCII Code of character (from 0-255) and same way getting the Char from Ascii code (from 0-255).

I have created following functions to achieve the same in C# but it is not returning correct results. Value returned by the RetAsciiCode is coming in thousands instead of between 0-255.

Equivalent values in VB are given below

? Asc(CurrentChar)


? Asc(CurrentChar)


? Asc(CurrentChar)


Pls help in solving this problem.

publicint RetAsciiCode(string MyString)


if (MyString.Length == 0)

return 0;

elseif (MyString.Length > 1)

MyString = MyString[0].ToString();

int AsciiCodeO = (int)System.Convert.ToChar(MyString);

byte[] AsciiCodeB = System.Text.Encoding.ASCII.GetBytes(MyString);

//int AsciiCode = System.Convert.ToInt32(AsciiCodeB);

return AsciiCodeO;


publicstring RetAsciiChar(int AsciiCode)


return System.Convert.ToChar(AsciiCode).ToString();



12 Answers Found


Answer 1

The easiest thing to do would be to add the Microsoft.VisualBasic as a reference in your project.  Now you can use those commands in the context that might be most familiar to you.  Be sure to add a using statement to whatever file you need.

using Microsoft.VisualBasic;

public static intAsc(char String)

Member of Microsoft.VisualBasic.Strings


Returns an Integer value representing the character code corresponding to a character.


String: Required. Any valid Char or String expression. If String is a String expression, only the first character of the string is used for input. If String is Nothing or contains no characters, an System.ArgumentException error occurs.

Return Values:

Returns an Integer value representing the character code corresponding to a character.

Code Snippet

publicstaticint StringToASCII(string input)




publicstaticint CharToASCII(char input)




publicstaticchar ASCIIToString(int input)





Answer 2

I want to use this option as a last resort. Can't you suggest some c# equivalent  instead of relying on VB lib.

Answer 3

Characters in .NET are Unicode, not ASCII, so Unicode to ASCII conversion is an issue.

If you want the exact result from Asc, then I suggest adding a reference to the VisualBasic assembly.

Is there a reason why you want the translation from non ASCII characters to ASCII characters that Asc provides?


Answer 4

Asc takes into account the code page of the system.  A codepage is used for translation of ANSI values.

On a western code page Asc would operate in much the same way as System.Text.Encoding.GetDefault.GetBytes and returning the value of the first byte.  On DBCS code pages you Asc converts DBCS values that don't map to a single bytes, which will result in a 16-bit value.

Asc does something like this:

Code Snippet

publicstaticint Asc(char c)


int converted = c;

if (converted >= 0x80)


byte[] buffer = newbyte[2];

// if the resulting conversion is 1 byte in length, just use the value

if (System.Text.Encoding.Default.GetBytes(newchar[] {c}, 0, 1, buffer, 0) == 1)


            converted = buffer[0];




// byte swap bytes 1 and 2;

            converted = buffer[0] << 16 | buffer[1];



return converted;



Answer 5

Finally, I have used reflector to disassemble the code and and for these two funcitons I have pasted the code in my class. I hope I'm not violating any of the copyright rules by doing that, if that is the case then I will remove that and add a reference to VB assembly.

Reason for using this function is that this is a old program written in VB which translates a local non english font into unicode. Full code is written based on the ASCII code and after doing conversion everything was converted in c# except this asc  and chr  function.


Answer 6

The .NET 2.0 Framework license is a supplement to your Windows licence. All Windows licences that I've seen contain this clause:


reverse engineer, decompile, or disassemble the Product, except and only to the extent that it is expressly

permitted by applicable law notwithstanding this limitation.

So, yes, you're likely violating your license agreement.

Answer 7

One more question in this same context. I'm licensed user of both VS2005 as well as VS2008. Although I have installed VS2008 but I was not able to play much with it. Previously I heard that Ms was going to release source code of net framework with VS2008.

Is it supplied now with Vs 2008, kindly advs.


Answer 8

Vinodonly wrote:

One more question in this same context. I'm licensed user of both VS2005 as well as VS2008. Although I have installed VS2008 but I was not able to play much with it. Previously I heard that Ms was going to release source code of net framework with VS2008.

Is it supplied now with Vs 2008, kindly advs.

No, it's not included with VS2008.  VS2008 (with a hotfix) will access the symbols servers at Microsoft so you can debug some of the .NET Framework source.  See http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx for details on how to set it up.

Answer 9

Asc does something like this:

Code Snippet

publicstaticint Asc(char c)


int converted = c;

if (converted >= 0x80)


byte[] buffer = newbyte[2];

// if the resulting conversion is 1 byte in length, just use the value

if (System.Text.Encoding.Default.GetBytes(newchar[] {c}, 0, 1, buffer, 0) == 1)


            converted = buffer[0];




// byte swap bytes 1 and 2;

            converted = buffer[0] << 16 | buffer[1];



return converted;


Thanks for the code snippet. I did this to get a .NET string back from one ASCII char:
    static string Str(int t)
      byte b = 0;
      b = Convert.ToByte(t); //throws overflow exception if t > maxbyte value
      return System.Text.ASCIIEncoding.UTF8.GetString(new byte[] { b });

Hope this is helpful to my fellow old C programmers out there (char is int type in C).

Answer 10

To convert a character to ASCII in csharp just cast that character as an int.  This should give you the ascii code for that character.

char c = "s";
int asc  = (int)c;

p.s. not sure if my syntax is correct, but the functionality should be.

Answer 11

Use the following in your C# code:


1. using Microsoft.VisualBasic;


Add the reference to Microsoft.VisualBasic.

Use Strings.Asc(input) freely.


Answer 12

You don't need to reference the VB assemblies. The following has the same behavior as the VB6 functions.

staticshort Asc(string String)
  return Encoding.Default.GetBytes(String)[0];
staticstring Chr(int CharCode)
  if (CharCode > 255)
    thrownew ArgumentOutOfRangeException("CharCode", CharCode, "CharCode must be between 0 and 255.");
  return Encoding.Default.GetString(new[] { (byte)CharCode });


In VB 6 this code returned a string albeit comprised of what appears are control characters.

Private Sub Create_Read_Command_String()

    Command_ID = &H5                            ' 05H is the "Read Tag Data" command code
    Command_LenW = 6                            ' Command length in words
    Start_Address = 0                           ' Start address of the tag's R/W memory in this example
    Data_Len = 100                              ' Number of bytes to read in this example
    Command_Timeout = 2000                      ' Timeout in ms to perform the RFID command in this example
' MSB - LSB = overall length of command in words
    Command_String = Chr$(Command_LenW \ 256) & Chr$(Command_LenW Mod 256)
' MSB = AA fixed  -  LSB = command ID
    Command_String = Command_String & Chr$(&HAA) & Chr$(Command_ID)
' MSB = 00 fixed  -  LSB = SubNet node ID
    Command_String = Command_String & Chr$(&H0) & Chr$(Node_ID)
' MSB - LSB = command timeout in ms
    Command_String = Command_String & Chr$(Command_Timeout \ 256) & Chr$(Command_Timeout Mod 256)
' MSB - LSB = Start Address
    Command_String = Command_String & Chr$(Start_Address \ 256) & Chr$(Start_Address Mod 256)
' MSB - LSB = data length
    Command_String = Command_String & Chr$(Data_Len \ 256) & Chr$(Data_Len Mod 256)
End Sub

'The output looks like so
 ª Р  d

In VB.NET 2005 the code looks like so



Function Create_Read_Command_String(ByVal NodeId AsInteger, ByVal Command_TimeOut AsInteger, ByVal NumBytesToRead AsInteger, ByVal StartAddress AsInteger) AsString


Dim Command_ID AsInteger = RFID_COMMANDS.READ_COMMAND ' 05H is the "Read Tag Data" command code


Dim Command_LenW AsInteger = 6 'Command length in words


Dim Command_String AsString = String.Empty


Dim RetString AsString = String.Empty




' MSB - LSB = overall length of command in words
Command_String = Convert.ToChar(Command_LenW \ 256) & Convert.ToChar(Command_LenW Mod 256)


' MSB = AA fixed - LSB = command ID

Command_String = Command_String & Convert.ToChar(&HAA) & Convert.ToChar(Command_ID)


' MSB = 00 fixed - LSB = SubNet node ID

Command_String = Command_String & Convert.ToChar(&H0) & Convert.ToChar(NodeId)


' MSB - LSB = command timeout in ms

Command_String = Command_String & Convert.ToChar(Command_TimeOut \ 256) & Convert.ToChar(Command_TimeOut

Mod 256)


' MSB - LSB = Start Address

Command_String = Command_String & Convert.ToChar(StartAddress \ 256) & Convert.ToChar(StartAddress

Mod 256)


' MSB - LSB = data length

Command_String = Command_String & Convert.ToChar(NumBytesToRead \ 256) & Convert.ToChar(NumBytesToRead

Mod 256)

RetString = Command_String


Catch ex As Exception

RetString =





Return RetString



'The output from this is

I am communicating with an Industrial RFID device and when I use VB6, it works, yet when I use VB.NET it does not.

I have tried the Chr function, the ChrW function to no avail.  

Does anyone have an idea of what is transpiring? Is there a function that I'm not aware of that could help solve this dilemma?



Hi, I would like to change all field values when the value displayed is chr(34) to chr(32) -empty string/

I am using .CR 2010 for .NET.

any suggestion on how to do it in the most efficiant way will be welcomed.


HI,everyone. Which key the function chr(0) represent.Thands!

What is the equivalent function in C# for the function IsDate in VB?



Anyone aware of a Windows Mobile (.NET 2.0 or 3.5) equivalent function of:

Dim WshShell
Set WshShell = WScript.CreateObject("Wscript.Shell")
WshShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", "laserjet.bmp"
WshShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters", 1, False
Set WshShell = Nothing

Basically, I want Windows Mobile 6.1 to envoke a system refresh.  Similar to the above VBScript code, so the registry is current.

Thank You.


I have a large data set returned in code that I am prepping for a client-side SSRS report.  I use the data set for a few different things, but now I need to be able to add a ranking by category.  I can do it easily in SQL using the ROW_NUMBER function, but I cannot figure out how to do the same thing in LINQ.  Here is the basic query in SQL:
    SUM(Sales) AS Total Sales
FROM MyTable
GROUP BY Category, Salesperson
I can easily do everything in LINQ but that function, and I don't want to have to pull the data all over again from SQL as it takes a long time as it is.  Does anyone have any suggestions?

I have a Delphi DLL with an exported function declared like this:

function IsRemoteUsb: Byte; cdecl;

I can successfully call this function from a C++ application written in Visual C++ 6 (!), using this declaration:

extern "C" {
  unsigned char __declspec(dllimport) IsRemoteUsb(void);

Now I need to call the function from straight C code.  I'm not sure how to define the call in C (again, Microsoft Visual C++ 6), so I tried this:

typedef unsigned char (__stdcall *IsRemoteUsb)(void);

 HMODULE hLib = LoadLibrary("MyLib.DLL");
 if (hLib)
  IsRemoteUsb Func = (IsRemoteUsb)GetProcAddress(hLib, "IsRemoteUsb");

  if (Func != NULL)
     unsigned char ret = Func();

The program crashes when the call to Func is made.  I also tried the following:

typedef unsigned char (__cdecl *IsRemoteUsb)(void);

It also crashes.

Could someone please tell me how I should declare this in C?  I'd prefer not to have to load MyLib.dll using LoadLibrary as well.

Thanks in advance!


Hi Folks

Is there a DAX expression in Powerpivot tables that performs the same function as the NETWORKDAYS function in Excel?


Many thanks 




Hi All,

I have written a LINQ Query with Contains method in where condition. How can i skipp that perticular condition when the value is NULL?

Below is my LINQ query.



test = (from w in db.WorkOrderPools


where w.Completed == false

&& (w.Skipped ==

null || w.Skipped != true)

&& site.Contains(w.SiteId.ToString())

&& woType.Contains(w.WOType.ToString())

--> Here, if we have no values for SIteId, how can i skipp that line from where condition? (in SQL Server, we can do this by using COALESCE().


Thanks in Advance,

Sateesh Nagalla,

80088 30603

Hello, I am looking for a way to do the MSSQL T-SQL equivalent of the MySQL aggregate function: group_concat().

We are running SQL 2005 Express. Is there a pure T-SQL way to do this, or if not, a way to create a new custom aggregate function?





Is there a sol'n?  I have looked all over the net and have not been able to find a thing.

Here is copy Access code..

SELECT ID, [Academic Year], Term, Location, [Student Section], [Creation Date], First(Date) AS FirstOfDate, First(Status) AS FirstOfStatus, First([Reg Status]) AS [FirstOfReg Status], First([Status Date]) AS [FirstOfStatus date]
FROM [StudentRecord]
GROUP BY ID, [Academic Year], Term, Location, [Student Section], [Creation Date]
ORDER BY ID, [Academic Year], Term, Location, [Student Section], [Creation Date], First(Date) DESC , First(Status) DESC;

I hope this helps.



I am migrating my postgres database to MS SQL Server 2005. I had some sql queries that used for reporting module in my application.

These queries contains fields of data type "interval" in postgres. Also it has sum and avg aggregate functions on these fields.

I searched for equivalent functionality in MS SQL Server 2005. But it seems that aggregate functions like sum and avg in MS SQL Server 2005 works either with int, float,decimal,money and not with datetime rather time.

I would like to know how can I do this. Also is there any equivalent function to justify_hours in postgres

Thanks in advance. Any help appreciated.


I have created a VB 6 dll and registered it on my m/c. When i am trying to access the component from an asp page using server side coding its running fine but when trying to access the same dll from vb script code thru same asp page it's throwing error saying Activex component cannt create object.

Please help.


what is the Equivalent of a Static class in VB.Net. Is it Modules?

And When i used one of the C#  to VB.Net conversion tools then the code

"Public Static class Class1 " was converted to

"Public NotInheritable Class Class1"

Is the Non-Inheritable class same as Static class. Please Help


Hello everyone.


I have three questions.


I would like to now what the equivalent of this code would be in C#

For FirstChar = 0 To sw.Length - 1

Secondly I would like to know what the C# version of Friend with events is.


And lastly I would like to know if C# has a Stopwatch object like VB.NET.


Thanks in advance.


Jai Brown.


Ok i seen another answer similar question to mine but it didn't go further to answer my real question so here goes. The "Dynamic" keyword in c# 4.0 is a great feature. It looks like there is no equivalent in vb.net. In the other thread people suggesting just turning option strict off and you would, in essence, be doing the same thing. I see two problems with this:

1) Most people are going to want to turn option strict off the the entire project just want to do it in a couple places
2) What i'm trying to do is return / accept anonymous types.

My question really is around point 2 above. For example you can return results from LINQ and not worry that the return could potentially have a different structure. I tested this with dynamic & c# and it worked great. This is probably what i will use dynamic keyword for the most in C#. Is there any way to do this in vb.net that i'm not seeing?


can someone tell me the (mfc) c++ equivalents for the char datatype + cchar method?

thanks for your help


 Hello Everyone and thanks for your help in advance.  I am trying to convert a code block into VB.Net from C# but can't get it right.  Part of the problem is the use of Static methods which I can't seem to get the equivalent.  Here is the code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Web;

namespace RewriteModule

    public class RewriteContext
        // returns actual RewriteContext instance for
        // current request
        public static RewriteContext Current
                // Look for RewriteContext instance in
                // current HttpContext. If there is no RewriteContextInfo
                // item then this means that rewrite module is turned off
                    return (RewriteContext)HttpContext.Current.Items["RewriteContextInfo"];
                    return new RewriteContext();

        public RewriteContext()
            _Params = new NameValueCollection();
            _InitialUrl = String.Empty;

        public RewriteContext(NameValueCollection param, string url)
            _InitialUrl = url;
            _Params = new NameValueCollection(param);

        private NameValueCollection _Params;

        public NameValueCollection Params
            get { return _Params; }
            set { _Params = value; }

        private string _InitialUrl;

        public string InitialUrl
            get { return _InitialUrl; }
            set { _InitialUrl = value; }


Any help is greatly appreciated.



Dear Team,


If we need to comment more than one line we'll use the following syntax in C#.NET.


/* this.comboBox1 = new System.Windows.Forms.ComboBox();

this.button1 = new System.Windows.Forms.Button();

this.dataGridView1 = new System.Windows.Forms.DataGridView();

this.textBox1 = new System.Windows.Forms.TextBox();

this.panel3 = new System.Windows.Forms.Panel();

this.textBox2 = new System.Windows.Forms.TextBox();

this.pictureBox1 = new System.Windows.Forms.PictureBox();




What is the equivalent for this in VB.NET. I know the following syntax, I'm expecting other than this

' .ToolTipIcon = Tipicon' .ShowAlways = False' .IsBalloon = True
I look forward to hear from you.


Hi I am VB6 programmer new to VB.NET.  I was wondering what the equivalent of the VB6 object reference in VB.NET is.

Here is a sample code (in VB6) of what I would like to do.

Dim obj as Object

Dim Class1 as cls1

Dim Class2 as cls2

If ChoiceA Then

     Set Class1 = New cls1

     Set obj = cls1


     Set Class2 = New cls2

     Set obj = cls2

End If

obj.ID = MyInteger

obj.Name = "MyName"

If I posted in the wrong forum sorry, I couldn't find a VB6 section.




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure