You have some really, really basic concepts you're attempting to understand. I'll attempt to break the question apart with some clarification and add to the two exceptional answers you've received.
Cast:
The conceptual notion of casting is incredibly important, as this concept is imperative in modification of your data. Your specifically asking about:
Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the
conversion, or when the conversion might not succeed for other
reasons. Typical examples include numeric conversion to a type that
has less precision or a smaller range, and conversion of a base-class
instance to a derived class.
In your example, your implementing the as Rectangle
. For the sake of simplicity I'm going to use an easier data type. The as
cast when it converts it won't create the following error:
Instead it returns a null
when it fails, which is a clean way to fail silently. Which meets particular needs in several instances where you don't want an Exception to break your user flow.
Example (A):
int valid = 0;
string number = valid as string;
Example (B):
string valid = 1;
int number = valid as string;
Example (C):
string valid = "valid";
int? number = valid as int?;
All three of those examples are valid, however in Example (C) you'll notice two items:
int?
- Allows a null
for an int
.
- It also isn't breaking your application, as the failed cast will return
null
.
The other approach for casting would be to apply (int)
or (string)
to explicitly force the data to that type. So it will either succeed and or throw exception. For example:
Example (D):
string invalid = "Fail"
int? number = (int?)invalid;
That would cause the Invalid Cast Exception to be thrown. Example (C) and Example (D) are two simple comparisons for the difference between cast.
Hopefully this provides better information for you.