Click here to Skip to main content
Sign Up to vote bad
good
See more: C#4.0
how to convert an integer string to an integer
Posted 9 Feb '13 - 20:17
Edited 9 Feb '13 - 21:00
Jibesh15.6K


3 solutions

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[^].
  Permalink  
Comments
Mehdi Gholam - 10 Feb '13 - 2:27
Just posted the same, 5'ed
Abhinav S - 10 Feb '13 - 2:29
Thank you :).
Espen Harlinn - 10 Feb '13 - 18:38
And another from me :-D
Abhinav S - 11 Feb '13 - 0:30
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
  Permalink  
Comments
Mehdi Gholam - 10 Feb '13 - 8:57
5'ed
Andreas Gieriet - 10 Feb '13 - 10:53
Thanks for your 5! Andi
Espen Harlinn - 10 Feb '13 - 18:39
5'ed!
Andreas Gieriet - 10 Feb '13 - 18:42
Thanks for your 5! Cheers Andi
Use int.Parse():
string str = "123456";
int i = int.Parse(str);
  Permalink  
Comments
Abhinav S - 10 Feb '13 - 2:29
My 5.
Andreas Gieriet - 10 Feb '13 - 5:12
Try to avoid plain Parse(...) calls: use TryParse(...) instead. See my solution#3. Cheers Andi
Espen Harlinn - 10 Feb '13 - 18:39
5'ed!
Mehdi Gholam - 11 Feb '13 - 1:08
Cheers Espen!

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 OriginalGriff 146
1 Richard MacCutchan 145
2 Sergey Alexandrovich Kryukov 134
3 Tadit Dash 134
4 Santhosh G_ 120
0 Sergey Alexandrovich Kryukov 10,348
1 OriginalGriff 7,965
2 CPallini 4,241
3 Rohan Leuva 3,522
4 Maciej Los 3,184


Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 10 Feb 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid