Click here to Skip to main content
12,063,909 members (56,936 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# C#4.0
how to convert an integer string to an integer
Posted 9-Feb-13 21:17pm
Edited 9-Feb-13 22:00pm
Jibesh17.1K
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 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.
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 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
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 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160204.4 | Last Updated 10 Feb 2013
Copyright © CodeProject, 1999-2016
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