views:

63

answers:

4

What is the big difference between parsing and typecasting? I try to use type casting to a string and it gives me error.

Something like this:

string str = "10";
int i = (int) str;
+1  A: 

For type casting to work the types need to be compatible:

object str = 10;
int i = (int) str;

Parsing is conversion between different types:

string str = "10";
int i = int.Parse(str);
Darin Dimitrov
so that means I can only use casting in short, double, long etc.?
Rye
You can use type casting with any type given that the type you are casting from is the same as the type you are casting to. As far as parsing is concerned there are different overloads of the Parse method which allow you to convert a string to integer, float, decimal, ...
Darin Dimitrov
just a follow up question, so parsing is much better?
Rye
It depends on what you are trying to do. If you need to convert a string to integer than you don't have the choice, you need to parse it.
Darin Dimitrov
A: 

Casting works when the objects share some piece of inheritance. But in your case

int i = (int) str;

You are dealing with implicit automatic conversion. In which the compiler will automatically widden/losen a .NET built-in type. For a complete guide go here and look for Converting and Casting

Int32.Parse(...

Parsing is for when they are two unrelated objects, but there is a way of converting one way to another.

Nix
A: 

Try this comprehensive explanation by Marc Gravell.

Oren A
A: 

This seems to be a recurrent question on SO, you can find more details here: difference between type conversion and type casting?

vc 74