Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
how to convert an integer string to an integer
Posted 9-Feb-13 21:17pm
Edited 9-Feb-13 22:00pm
Jibesh16.6K
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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 at 10-Feb-13 2:27am
   
Just posted the same, 5'ed
Abhinav S at 10-Feb-13 2:29am
   
Thank you :).
Espen Harlinn at 10-Feb-13 18:38pm
   
And another from me :-D
Abhinav S at 11-Feb-13 0:30am
   
Thank you.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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 at 10-Feb-13 8:57am
   
5'ed
Andreas Gieriet at 10-Feb-13 10:53am
   
Thanks for your 5!
Andi
Espen Harlinn at 10-Feb-13 18:39pm
   
5'ed!
Andreas Gieriet at 10-Feb-13 18:42pm
   
Thanks for your 5!
Cheers
Andi
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Use int.Parse():
string str = "123456";
int i = int.Parse(str);
  Permalink  
Comments
Abhinav S at 10-Feb-13 2:29am
   
My 5.
Andreas Gieriet at 10-Feb-13 5:12am
   
Try to avoid plain Parse(...) calls: use TryParse(...) instead. See my solution#3.
Cheers
Andi
Espen Harlinn at 10-Feb-13 18:39pm
   
5'ed!
Mehdi Gholam at 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)

  Print Answers RSS
0 OriginalGriff 230
1 PIEBALDconsult 150
2 DamithSL 125
3 Andreas Gieriet 90
4 Jochen Arndt 90
0 OriginalGriff 5,790
1 DamithSL 4,601
2 Maciej Los 4,012
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,195


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 10 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100