Loïc Wolff
Loïc Wolff

Reputation: 3312

Is there a difference between casting an int.Parse() to long and using long.Parse?

I've just stumbled on some code where the developer used

fooBar((long)int.Parse(someVariable));

The fooBar function is just waiting a long as a parameter and use it for an SQL query.

Is there any difference between that and using long.Parse(...)?

Upvotes: 1

Views: 193

Answers (4)

cHao
cHao

Reputation: 86505

The main difference is that with int.Parse, you're pretty much guaranteed a number within the range of an int. If the number is outside that range, an OverflowException will be thrown by int.Parse (while long.Parse would happily accept it, as long as the number's within long's range).

Upvotes: 4

MRM
MRM

Reputation: 435

when you use long.Parse the result of function is int64 but when you use int.Parse the result is int32.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190945

The difference is if someVariable represents a value that can't fit into an int.

Upvotes: 4

Ray
Ray

Reputation: 46585

Yes, long.Parse will handle numbers that are larger than an int. So it's preferable, unless you want an exception if the number can't fit in an int.

Also the casting from the int to long is unnecessary since an implicit cast exists.

Upvotes: 4

Related Questions