tags:

views:

104

answers:

2
+3  Q: 

Using Int32.Parse

Why is there a need to convert a value (for example short) to string, and then to Int32. Why can it not be converted from short to Int 32?

+4  A: 

You don't need this because you can cast:

short shortNumber = 11;
int notAsShortNumber = (int)shortNumber;
bobbymcr
No, there is no need for the explicit cast.
Noon Silk
It certainly makes it clear what you intended.
ChaosPandion
I have seen code like this: shortvalue = 100 integervalue = 1000 integervalue = integervalue + int32.Parse(shortvalue.ToString()); Why is the shortvalue being converted to string, and then to Int32?
DotNetRookie
It is simply from lack of experience.
ChaosPandion
DotNetRookie: It's bad code. It is not required, and is just plain wrong.
Noon Silk
Its only bad code if you know better.
ChaosPandion
shortvalue = 100;integervalue = 1000;integervalue = integervalue + int32.Parse(shortvalue.ToString()); Why is the shortvalue being converted to string, and then to Int32?
DotNetRookie
ChaosPandion: No, it doesn't make it clear, it makes it confusing, because there is no need for the cast. It's better to understand how the language works, then things are truly clear.
Noon Silk
When you see this you cannot say he mistakenly set two different value types equal to each other.
ChaosPandion
ChaosPandion: No, it's bad code regardless! Everyone needs to learn, and there is nothing wrong with being wrong, but it's just foolish to act like it isn't bad to do that. What an odd statement.
Noon Silk
ChaosPandion: I will not continue this useless argument.
Noon Silk
extraneous != bad
Rex M
Rex: I'm certain you'd agree that code that takes a `short`, makes it a `string`, then calls `TryParse` to get it as an `int` is bad. It's not personal against anyone, it's just flat-out bad.
Noon Silk
Oh is that what your getting so worked up about? I am in full agreement. When a noobie is learning however the only bad code is no code. Once he is shown the proper way he should never do such things again.
ChaosPandion
@silky I think everyone else thinks you're talking about `int i = (int)s`
Rex M
Rex: Can't really imagine why, as when you read back, my response that started the argument is clearly address directly to DotNetRookie, about the code he posted in the comment. Anyway, at least it's clear now. And for completeness, I don't consider that, `int i = (int) s`, truly bad, it's just not required. Glad we all agree.
Noon Silk
+8  A: 

There is no need to even to any sort of explicit conversion:

short s = 23;
int k = s;

Also, any numeric literals (without any sort of suffix) are int32s anyway.

-- Edit

The reason an explicit cast isn't required is because a short is always smaller than an int, thus a short will always completely fit into the size of an int, so no potential loss of data.

Noon Silk