Convert.ToInt32(String) With an Empty String
Lately, I have been struggling with the Convert.ToInt32 overload that takes a String as a parameter. Basically, it’s the same as Int32.Parse, except that if the given String is null, it returns 0 instead of throwing a FormatException. That’s quite cool, but Convert.ToInt32 still throws when the argument is an empty String…
Now, my particular case is that I’m retrieving data from Sharepoint, and that the field retrieved can be empty if the user left it blank (when retrieving the field trough a DataTable).
The workaround to that issue is actually pretty silly: just add a 0 at the beginning of the parsed String, and it will work all the time (and return 0 when the string is empty, as it does with null). Now mind you, this only works with positive integers. If your integer is negative, adding a 0 in front of it will make the Convert.ToInt32 throw a FormatException again…
String theInt = ""; //Throws... Console.WriteLine(Convert.ToInt32(theInt)); //Doesn't throw Console.WriteLine(Convert.ToInt32("0" + theInt)); theInt = Int32.MaxValue.ToString(); //Doesn't throw Console.WriteLine(Convert.ToInt32("0" + theInt)); theInt = Int32.MinValue.ToString(); //Throws again... Console.WriteLine(Convert.ToInt32("0" + theInt));
So, this is safe to use if you are certain that the integer in the String is always positive.
PS: note that I always write String with a capital S in my code (and in text), this is a habit left from Java I guess…
blog comments powered by Disqus