Nullable is an struct. And i know structs cant be assigned 'null'. So how could we assign Nullable's object a null? What is the reason?
It doesn't actually accept a value of null
; it simply has syntactic sugar that allows it to act like it's null
. The type actually looks a bit like this:
struct Nullable<T>
{
private bool hasValue;
private T value;
}
So when it's initialized hasValue == false
, and value == default(T)
.
When you write code like
int? i = null;
The C# compiler is actually doing this behind the scenes:
Nullable<T> i = new Nullable<T>();
And similar checks are made when casting null
to an int?
at run-time as well.
Further Reading
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.