Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
how to convert from string to integer in c# ?
Posted

Very interesting thing in conversion is Input string, here some examples to understand convertion..

1.
C#
int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105

2.
C#
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105

3.
C#
try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.

4.
C#
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);
// Output: Int32.TryParse could not parse 'abc' to an int.


From above example you come to know that input string should be in correct format..

You can refer below link..
http://msdn.microsoft.com/en-us/library/bb397679.aspx[^]
 
Share this answer
 
use Int32.TryParse[^] or Inst32.Parse[^]
C#
int number;
bool result = Int32.TryParse("string value to convert", out number);
//or
number = Int32.Parse("string value to convert");
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 13-Feb-13 18:13pm    
5ed. Parse (which is also worth mentioning) and TryParse is much better than convert because it tells us what really happens. "Convert" is a really bad word literally haunting this forum.
—SA
Jibesh 13-Feb-13 18:22pm    
That is reasonable,updated my answer.

Thanks.
Sergey Alexandrovich Kryukov 13-Feb-13 18:38pm    
Nice. Thank you.
—SA
fjdiewornncalwe 14-Feb-13 9:01am    
+5. TryParse is the way to go.
Jibesh 14-Feb-13 12:11pm    
Thank You marcus
int number = Convert.ToInt32("string to convert");
 
Share this answer
 
v3
C#
public static bool TryParse(
    string s,
    out int result
)
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 18-Feb-13 8:43am    
I'm not sure what value this solution adds considering the quality of solutions 2 & 4.
Care to elaborate what you are trying to accomplish here.

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