Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Casting, Parsing and Converting [duplicate]

Tags:

c#

I have been working on some code for a while. And I had a question: What's the difference among casting, parsing and converting? And when we can use them?

like image 364
Spoon Yukina Avatar asked Sep 23 '12 13:09

Spoon Yukina


People also ask

What is the difference between casting and parsing?

Casting means taking a variable of one type and turning it to another type. There are obviously some combinations which can be cast, and some which cannot. Parsing means reading text and deciding what the different parts of it mean.

Is casting the same as converting?

1. In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler.

What is the difference between parse and convert in C#?

Parse and Convert ToInt32 are two methods to convert a string to an integer. The main difference between int Parse and Convert ToInt32 in C# is that passing a null value to int Parse will throw an ArgumentNullException while passing a null value to Convert ToInt32 will give zero.

What is casting and conversion in Java?

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.


1 Answers

Casting is when you take a variable of one type and change it to a different type. You can only do that in some cases, like so:

string str = "Hello";
object o = str;
string str2 = (string)o;  // <-- This is casting

Casting does not change the variable's value - the value remains of the same type (the string "Hello").

Converting is when you take a value from one type and convert it to a different type:

 double d = 5.5;
 int i = (int)d;    // <---- d was converted to an integer

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. For instance, converting the string "123" to the number 123, or the string "Saturday, September 22nd" to a DateTime.

like image 101
zmbq Avatar answered Oct 11 '22 07:10

zmbq