Tony Johansson said:
If I want to convert a string to Int32 I can't use cast like this
string s = 10;
int number = (int)s;
but have to use parse or Convert like this
Convert.ToInt32(s) or
Int32.Parse(s)
So why does not .NET support casting like this
string s = 10;
int number = (int)s;
Actually what you mean is why doesn't C# support this, because VB.Net does.
So in VB.Net you could write
dim s as string = "10"
dim number as integer = s
and it works fine. If anything it works a little too well, because it means
you can mix your types and not notice - until your string no longer contains
a number and then you get a runtime exception thrown. So, from experience I
would say that your code is logically cleaner and clearer if it isn't
supported and you have to do the conversion explicitly if that's what you
want.
As for why (int)s isn't supported - I think both Arnie and Marcel have good
points. Paraphrasing, Arne said that casting is between similar data types,
and Marcel that the conversion is ambiguous - which is why I often don't use
Convert.ToInt32 because it doesn't quite do what I want with the data I'm
using.