Reputation: 41259
In our own Jon Skeet's C# in depth, he discusses the 3 ways to simulate a 'null' for value types:
It is mentioned that nullable types use the third method. How exactly do nullable types work under the hood?
Upvotes: 21
Views: 4491
Reputation: 564851
Nullable<T>
works by providing two fields:
private bool hasValue;
internal T value;
The properties work from those. If you set it to null
, hasValue is set to false.
Upvotes: 4
Reputation: 1064084
Ultimately, they are just a generic struct with a bool flag - except with special boxing rules. Because structs are (by default) initialized to zero, the bool defaults to false (no value):
public struct Nullable<T> where T : struct {
private readonly T value;
private readonly bool hasValue;
public Nullable(T value) {
this.value = value;
hasValue = true;
}
public T Value {
get {
if(!hasValue) throw some exception ;-p
return value;
}
}
public T GetValueOrDefault() { return value; }
public bool HasValue {get {return hasValue;}}
public static explicit operator T(Nullable<T> value) {
return value.Value; }
public static implicit operator Nullable<T>(T value) {
return new Nullable<T>(value); }
}
Extra differences, though:
EqualityComparer<T>
, Comparer<T>
etc)Nullable<Nullable<T>>
)Upvotes: 37