Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can the as operator be used with Nullable<T>?

Tags:

According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types". Since Nullable is actually a value type, I would expect as not to work with it. However, this code compiles and runs:

object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7

Is this correct behavior? Is the documentation for as wrong? Am I missing something?

like image 225
recursive Avatar asked Aug 18 '11 15:08

recursive


People also ask

How do you make an int nullable in C#?

As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable<t> where T is a type.

What is the purpose of a nullable type?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false .

Does HasValue check for null?

HasValue: This property returns a bool value based on that if the Nullable variable has some value or not. If the variable has some value, then it will return true; otherwise, it will return false if it doesn't have value or it's null.

Why do we use nullable types in C#?

We are using nullable types when we need to represent an undefined value of an underlying type. While Boolean values can have either true or false values, a null in this case means false as there is no undefined value. When you have a database interaction, a variable value can be either undefined or missing.


2 Answers

Is this correct behavior?

Yes.

Is the documentation for as wrong?

Yes. I have informed the documentation manager. Thanks for bringing this to my attention, and apologies for the error. Obviously no one remembered to update this page when nullable types were added to the language in C# 2.0.

Am I missing something?

You might consider reading the actual C# specification rather than the MSDN documentation; it is more definitive.

like image 187
Eric Lippert Avatar answered Oct 02 '22 01:10

Eric Lippert


I read:

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

And boxing conversions.....

like image 26
Tigran Avatar answered Oct 02 '22 02:10

Tigran