Difference between int.Parse , Convert.ToInt32 and int.TryParse
int.Parse(string s)
- Simply,
int.Parse (string s)
method converts thestring
to integer. - If
string s
isnull
, then it will throwArgumentNullException
. - If
string s
is other than integer value, then it will throwFormatException
. - If
string s
represents out of integer ranges, then it will throwOverflowException
.
Example:
- class Program
- {
- static void Main(string[] args)
- {
- string Num1="123";
- string Num2=null;
- string Num3="123.6743";
- string Num4="34909564545464509123409";
- int finalResult;
- finalResult = int.Parse(Num1); //success
- finalResult = int.Parse(Num2); // ArgumentNullException
- finalResult = int.Parse(Num3); //FormatException
- finalResult = int.Parse(Num4); //OverflowException
- }
- }
Convert.ToInt32(string s)
- Simply,
Convert.ToInt32(string s)
method converts thestring
to integer. - If
string s
isnull
, then it will return0
rather than throwArgumentNullException
. - If
string s
is other than integer value, then it will throwFormatException
. - If
string s
represents out of integer ranges, then it will throwOverflowException
.
Example:
- class Program
- {
- static void Main(string[] args)
- {
- string Num1="123";
- string Num2=null;
- string Num3="123.6743";
- string Num4="34909564545464509123409";
- int finalResult;
- finalResult = Convert.ToInt32(Num1);
- finalResult = Convert.ToInt32(Num2);
- finalResult = Convert.ToInt32(Num3);
- finalResult = Convert.ToInt32(Num4);
- }
- }
int.TryParse(string s,Out)
- Simply int.TryParse(string s,out int)method converts the string to integer out variable and returns true if successfully parsed, otherwise false.
- If string s is null, then the out variable has 0 rather than throw ArgumentNullException.
- If string s is other than integer value, then the out variable will have 0 rather than FormatException.
- If string s represents out of integer ranges, then the out variable will have 0 rather than throw OverflowException.
Example
- class Program
- {
- static void Main(string[] args)
- {
- string Num1="123";
- string Num2=null;
- string Num3="123.6743";
- string Num4="34909564545464509123409";
- int finalResult;
- bool output;
- output = int.TryParse(Num1, out finalResult); // 9009
- output = int.TryParse(Num2, out finalResult); // 0
- output = int.TryParse(Num3, out finalResult); // 0
- output = int.TryParse(Num4, out finalResult); // 0
- }
- }
What is the difference between Convert.ToInt32 and (int)?
(int)foo
is simply a cast to the Int32
(int
in C#) type. This is built into the CLR and requires that foo
be a numeric variable (e.g. float
, long
, etc.) In this sense, it is very similar to a cast in C.Convert.ToInt32
is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int
(most notably, parsing a string
). You can see the full list of overloads for this method here on MSDN.
No comments:
Post a Comment