9

How can we implement a nullable type in C# if we didn't have this feature in C#?

4 Answers 4

10

Nullable Implementation for prior .NET 2.0

Sign up to request clarification or add additional context in comments.

Comments

5

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.)

1 Comment

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

Nullable is a generic type. Without generics it is not possible to implement a nullable like that and wouldn't really make sense.

Comments

0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.