How can we implement a nullable type in C# if we didn't have this feature in C#?
A:
Nullable is a generic type. Without generics it is not possible to implement a nullable like that and wouldn't really make sense.
bitbonk
2010-02-04 13:07:22
A:
You can't, without attaching business rules to existing values in the data type. eg. int.MinValue can be used as a placeholder, but what if you need this value? If you have a rule where all values are positive, it could work, but not as "nullable".
Program.X
2010-02-04 13:08:15
+3
A:
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.
Heinzi
2010-02-04 13:13:28
you can use comparison - as long as you override eg. needed operator or implement the correct interface
Andreas Niedermair
2010-02-04 13:26:17