How can we implement a nullable type in C# if we didn't have this feature in C#?
4 Answers
You can wrap a native type into a struct (quick example to give you an idea, untested, lots of room for improvement):
public struct NullableDouble {
public bool hasValue = false;
private double _value;
public double Value {
get {
if (hasValue)
return _value;
else
throw new Exception(...);
}
set {
hasValue = true;
_value = value;
}
}
}
Clearly, you won't get the syntactic sugar of newer C# versions, i.e. you have to use (See Andreas' comment.)myNullableDouble.hasValue instead of myNullableDouble == null, etc.