tags:

views:

221

answers:

4

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
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
+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 myNullableDouble.hasValue instead of myNullableDouble == null, etc. (See Andreas' comment.)

Heinzi
you can use comparison - as long as you override eg. needed operator or implement the correct interface
Andreas Niedermair