Rss Feed

Char to Int vs String to Int
Tue, Sep 29th, 2009

In C#, converting a char to an int produces it's unicode value. Converting a string to an int, produces it's integer value. This can be confusing! For example, pretend you want the first digit of a number:

The wrong way:
    int number = 10;
    int firstDigit = Convert.ToInt32(number.ToString()[0]); 

    Assert.AreEqual(1,firstDigit) //fails: firstDigit == 49
 
The right way:
    int number = 10;
    int firstDigit = Convert.ToInt32(number.ToString()[0].ToString()); //add an extra ToString()
    Assert.AreEqual(1,firstDigit) //passes 


<.NET>

Read Comments



Older Posts
© 2009-2012 Ben Ford