Last post Sep 27, 2013 11:21 PM by firemyst
Mar 07, 2011 02:05 PM|afache|LINK
I am using the following way to convert a string to int in C#
string x = "550";
int id = Convert.ToInt32(x)
What if I had a huge number that I am converting (larger than 32 bits)? Is there a better way to convert from string to Int where I will not get an error no matter how small or large is my integer value is?
Mar 07, 2011 02:24 PM|smirnov|LINK
Use Int64 data type
and you can use TryParse
Mar 07, 2011 02:28 PM|Shuvo Aymon|LINK
you may try Convert.ToInt64
Mar 07, 2011 02:29 PM|sansan|LINK
no matter how small or large is my integer value is?
You can use long.Parse
string x = "550";long id = long.Parse(x);
Mar 07, 2011 08:26 PM|PaulLinton|LINK
How much larger than 32 bits? 100 bits? 1000 bits? What do you want to happen when it is larger than 32 bits? Do you want an indication than it is too big for 32 bits or do you actually not want an int as a result of the conversion?
Mar 07, 2011 10:38 PM|cnranasinghe|LINK
It is better to use tryParse instead of Convert. Convert create exception if conversion is failed.
try something like following
string str = "232";
int.TryParse(str, out intValue);
Mar 09, 2011 03:56 AM|ptsivakumar|LINK
use the BigIntger in .NET 4 you can get the idea from following URL,
Mar 10, 2011 04:15 AM|gunnala|LINK
Here is what i would suggest . Not only for string to int, You can use it for all conversion.
public class ConvestionUtility
public static T GetValueAs<T>(object value, T defaultValue)
return (T)Convert.ChangeType(value, typeof(T));
Int64 i = ConvestionUtility.GetValueAs<Int64>("550", 0);
Sep 27, 2013 11:21 PM|firemyst|LINK
I know this post has been answered already, but for those who are looking for benchmarks, he benchmarks several different ways to convert a string to an int:
What's interesting is the fastest way isn't using any of the native C# methods Convert.ToInt32(), int.TryParse(), or int.Parse().
Definitely worth a read for those that are curious.