3

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;
Rye
  • 2,273
  • 9
  • 34
  • 43

2 Answers2

4

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • so that means I can only use casting in short, double, long etc.? – Rye Sep 27 '10 at 13:55
  • 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 Sep 27 '10 at 13:58
  • just a follow up question, so parsing is much better? – Rye Sep 27 '10 at 14:01
  • 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 Sep 27 '10 at 14:09
0

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
  • 57,072
  • 29
  • 149
  • 198