Why `as` is giving null for nullable value types?

From MSDN:

The code is equivalent to the following expression except that the expression variable is evaluated only one time.

expression is type ? (type)expression : (type)null

Since i is int? is false the as keyword will return (int?)null.


The types aren't equivalent and you get null, that is just how as works

However, you could just direct Cast

long? i = 10000;
var s = (int?)i;

// or even better make sure its *checked* 

var s = checked((int?)i);

Why does this work?

C# Language Specification 11.6.1 Nullable Conversions

...

Evaluation of a nullable conversion based on an underlying conversion from S to T proceeds as follows:

  • If the nullable conversion is from S? to T?:
  • If the source value is null (HasValue property is false), the result is the null value of type T?.
  • Otherwise, the conversion is evaluated as an unwrapping from S? to S, followed by the underlying conversion from S to T, followed by a wrapping from T to T?.

...

as does not do this, it checks the run-time types, if they are not equal returns null T?


Additional Resources

checked (C# Reference)

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

#Update from comments

I got that we can't convert and why we can't do I but why they are suggesting it is there any scenario where it will be useful i'e some random image link of Compiler Error CS0077 "The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)."

The reason is (in your image example) a value type can't be null it could never work with it. The thing you are missing is there are more complex examples of what could happen, you can define implicit operators on custom types, etc.

Tags:

C#

.Net