Reputation: 1748
'as' operator does not work with value types while 'is' does. why?
Upvotes: 3
Views: 116
Reputation: 30942
And as
is different from casting (excelent explanation here).
as
will never change the representation of the object itself, it will just change the type of the reference, while casting will change the type of the object itself if neccessary.
int? i = 3;
double? d = (double?)i;
is valid (and working) c# code, while
int? i = 3;
double? d = i as double?;
errors with "Cannot convert type 'int?' to 'double?' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"
Upvotes: 0
Reputation: 60744
Because the as
operator returns null
if the type is not matching, and a value type cannot hold a null
value.
For example
double d = myVariable as double;
if myVariable
is not a double
, d will be null
, and that is not an appropriate value for a double
.
Upvotes: 7