Impostor
Impostor

Reputation: 2050

Why is it invalid to cast an int to char with the as-operator?

In C# there are 2 ways of casting:

Why does the first line not compile and the second does?

Console.Write(49 as char);
Console.Write((char)49);

Upvotes: 2

Views: 114

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157048

From MSDN:

You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.

char is neither a reference type nor a nullable type. It can't set the output variable of 49 to null (when the conversion fails) since it isn't nullable. It would work with char? though, although useless in this situation.

Upvotes: 4

Related Questions