Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast versus parse

I've read a few related questions regarding this topic however none of them are making sense to me. As I understand it, in some cases you can use cast and parse interchangeably and achieve the same result.

Are there some general guidelines that can help me decide when to choose one approach over the other?

like image 498
Kory Avatar asked Sep 20 '10 11:09

Kory


People also ask

Is parsing the same as casting?

Casting does not change the variable's value - the value remains of the same type (the string "Hello"). Note that in this case, the conversion was done in the form of casting. Parsing is taking a string and converting it to a different type by understanding its content.

What is a parse method?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert.

What is a cast data type?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.

What is a cast in programming?

A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur, or the cast may fail at run time. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted.


1 Answers

You generally use Parse() on a string whose value represents a valid value of the type to which you are converting.

Casting, on the other hand, is better used when you have an object of a derived type but stored in a base variable, and need to use it as its more specific type.

That is, if you have "1234" you can Parse() that into an int. But if you have

object variable = 1234;

You should cast it to get it back as an int.

like image 71
Andrew Barber Avatar answered Oct 04 '22 22:10

Andrew Barber