Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Casting Exception

Tags:

c#

Why does the statement

(int)"84"

throw an exception and

Convert.ToInt32("84")

does not throw an exception?

like image 404
Asim Sajjad Avatar asked Dec 12 '22 22:12

Asim Sajjad


1 Answers

First one is plain casting, which is changing a type of an object (more technically speaking, this is not casting, but type conversion). .NET indeed allows some conversions (like int to long, etc), but this particular one is disallowed. The reason I think this is disallowed is because only a small subset of strings can be actually converted to int and rules for doing so will be very cumbersome. Additionally, this might not play well with internationalization.

The second is a method invocation, which actually parses string representation of an integer and constructs an int out of it.

like image 168
Anton Gogolev Avatar answered Dec 15 '22 14:12

Anton Gogolev