|
Converting from string to int Why not working (int)stringVariable?
I was asked with this question. Well, I think there are a lot of professionals who will not even think about it, but my suggestion is, if there's a person who can ask such a question, there must be a person, who will find a time and answer it.
OK, I always love to answer using my own words, not the copy-paste magic from MSDN library (by the way, it can be found at http://msdn.microsoft.com).
In C#, the type can be explicitly converted to the type of the same type - a little complicated sentence, right? But the truth! In this case, type int is a value-type, and type string is a reference-type. To convert from one to another, you must use static method int.Parse(string).
But be careful, it may throw an exception. If you want to handle the exception, you must use try-catch statement, or, a method that is more informational about parsing results, and as I think, more useful: int.TryParse(string, out int). Let's consider next code:
string s = "123"; int number = int.Parse(s); //all's ok
s = "123a"; number = int.Parse(s); //exception is thrown!!!
//solution is: //1) try { number = int.Parse(s); } catch(Exception ex) { MessageBox.Show(ex.Message); //or some other code to handle the exception }
//2) if (int.TryParse(s, out number); { //all's ok } else { MessageBox.Show("error converting from string to int"); //or some other code to handle the exception }
That's all. I hope you cought the idea.
|