What is the difference between int.Parse, Convert.Int32 and (int) type cast? Also, what are the best scenarios to use these 3? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the difference between int.Parse, Convert.Int32 and (int) type cast? Also, what are the best scenarios to use these 3?

12th Jun 2017, 6:45 PM
Ashish Kulkarni
Ashish Kulkarni - avatar
2 Answers
+ 2
Convert to int can handle, when the Value of a String is Null. It will simply give back Zero. Parse will throw an Exception and stop the Process. there is another Method called TryParse instead of Parse. it will simply give back zero instead of an Exception, ensuring, that your Programm won't break. string value 1; int value2; int.TryParse(value1, out value2) somehow i couldn't get the roundet Value of a Float when using TryParse directly to int. Instead i created another Float as a Temp Variable with float.TryParse("string") and used the Math.Round() method to transform float to int. I did this because, in case the string represent a float Value, the int.TryParse() method will give back 0. when you go this way, you will get the Rounded value out of the String. string value1; float temp; int value2; TryParse(value1, out temp); value2 = (int)Math.Round(temp); After my Experiments i came to the conclusion, that TryParse already has an implemented Try Catch Finally routine. You would use that in Case, when you do not know which kind of Data Type you get back from an Operation. The (int) Conversion seems to work only on numerical types, after Normalisation. ok, after hours of experimenting, please give a Feedback, if i am completely wrong ^^ cheers
13th Jun 2017, 12:58 PM
Benqen
Benqen - avatar
+ 1
1.) int.parse is used when you want to turn an input value thats a string into a int. Although thats one thing it can do there is much more when you get deeper in c# Best example: when using the Console.ReadLine(); function if the user types in an int value in and its placed back into a string block of code you will have many compile errors. You cannot place a int value into string unless parsed/converted. 2.) Convert.ToXXX methods, where xxx is .NET name lf the type. Best example: Convert.ToDouble Convert.ToBoolean 3.) (int) type cast is similar to the different methods for conversion such as the ones listed above int.parse and Convert.ToXXX. Although it is said that it is the most straightforward and efficient way . Best example: int.TryParse("11")
12th Jun 2017, 10:09 PM
Jonathan
Jonathan - avatar