Click here to Skip to main content
14,739,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to convert an integer string to an integer
Posted
Updated 9-Feb-13 22:00pm
v3

You can use the Convert.ToInt[^] method (choose the appropriate overload).

If you are not sure if the string is an integer or not, consider using TryParse[^].
   
Comments
Mehdi Gholam 10-Feb-13 2:27am
   
Just posted the same, 5'ed
Abhinav S 10-Feb-13 2:29am
   
Thank you :).
Espen Harlinn 10-Feb-13 18:38pm
   
And another from me :-D
Abhinav S 11-Feb-13 0:30am
   
Thank you.
Try to avoid Parse(...) or Convert.ToInt(...).
Use TryParse(...) instead.
Reason: only TryParse(...) allows to react on parsing mismatches, the other two functions throw exceptions in that case.

E.g. If you try to parse and set to a default in case of a parse failure occurs, you may use the following:
static readonly int DEFAULT_FOR_V = 123;
...
string s = "...";
...
int v = int.TryParse(s, out v) ? v : DEFAULT_FOR_V;
...


Cheers
Andi
   
Comments
Mehdi Gholam 10-Feb-13 8:57am
   
5'ed
Andreas Gieriet 10-Feb-13 10:53am
   
Thanks for your 5!
Andi
Espen Harlinn 10-Feb-13 18:39pm
   
5'ed!
Andreas Gieriet 10-Feb-13 18:42pm
   
Thanks for your 5!
Cheers
Andi
Use int.Parse():
string str = "123456";
int i = int.Parse(str);
   
Comments
Abhinav S 10-Feb-13 2:29am
   
My 5.
Andreas Gieriet 10-Feb-13 5:12am
   
Try to avoid plain Parse(...) calls: use TryParse(...) instead. See my solution#3.
Cheers
Andi
Espen Harlinn 10-Feb-13 18:39pm
   
5'ed!
Mehdi Gholam 11-Feb-13 1:08am
   
Cheers Espen!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900