idm
idm

Reputation: 1748

Why does "as" does not work on Value types while "is" does?

'as' operator does not work with value types while 'is' does. why?

Upvotes: 3

Views: 116

Answers (3)

SWeko
SWeko

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

codeandcloud
codeandcloud

Reputation: 55333

Check this: C# is and as operators

Upvotes: 3

Øyvind Bråthen
Øyvind Bråthen

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

Related Questions