none
how to convert char to int in C# RRS feed

All replies

  • You can always add a reference to Microsoft.VisualBasic and then use Strings.Asc

    https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.asc.aspx

    Sunday, December 3, 2017 2:55 PM
  • No conversion necessary:

    int i = 'c';

    A 'char' in C# is implicitly converted to most numeric types (except byte, sbyte, and short):

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/char


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter


    Sunday, December 3, 2017 3:04 PM
  • There are 3 ways you can convert 


    // Option 1
    int i ='c';
    
    // Option 2
    int x= Convert.ToInt32('c');
    
    // Option 3 
    int z=(int)'c';

    Thanks DoknJas for pointing me the casting issue


    Sunday, December 3, 2017 3:52 PM
  • There are 3 ways you can convert 


    // Option 1
    int i ='c';
    
    // Option 2
    int x= Convert.ToInt16('c');
    
    // Option 3 
    int z=(int)'c';



    Your second option should be "ToInt32" - casting to anything smaller than UShort may fail, depending on the character.

    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Sunday, December 3, 2017 5:05 PM
  • Unless your char is a number and you want the actual numeric value (you didn't specify in your question). Then use char.GetNumericValue():

    char c = '8';
    int val = (int)char.GetNumericValue(c);
    // val == 8


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com


    Sunday, December 3, 2017 5:28 PM
    Moderator
  • Hello miaad,

    Is there any update or any other assistance I could provide on this issue? you could mark the helpful reply as answer if there is any result. And if you have any concerns, please do not hesitate to let us know. Thank you for your understanding and patience!

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, December 24, 2017 6:48 AM
    Moderator