Nullable parameters in a generic class

92 views Asked by At

I know similar questions have been asked already but I did not find any solution for my particular issue.

I have a generic class with a constructor like this:

public ClampedValue(T value, T? min = default, T? max = default)

I would like to be able to pass in an integer as T and optionally a min and a max. If min or max are null they are to be ignored. I already noticed that

public ClampedValue(T value, T? min = null, T? max = null)

is not possible, can someone explain to me what I am doing wrong? I would expect T? = null to be valid but I get an error stating something about T not having standard conversion for null. I would understand T = null to be wrong because T can be a valueType, but T? explicitly asks for a nullable.

EDIT: Full class source

[Serializable]
    public class ClampedValue<T> : IClamp<T> where T : IComparable
    {
        internal T _value;

        [JsonIgnore]
        public T? Min { get; set; } = default;

        [JsonIgnore]
        public T? Max { get; set; } = default;

        public virtual T Value
        {
            get => _value;
            set
            {
                if (Max is not null && value.CompareTo(Max) > 0)
                {
                    _value = Max;
                }
                else if (Min is not null && value.CompareTo(Min) < 0)
                {
                    _value = Min;
                }
                else
                {
                    _value = value;
                }
            }
        }

        [JsonConstructor]
        public ClampedValue(T value)
        {
            _value = value;
        }

        public ClampedValue(T value, [AllowNull] T? min = default, [AllowNull] T? max = default)
        {
            Min = min;
            Max = max;

            if (Min is not null && Max is not null)
            {
                if (Min.CompareTo(Max) >= 0)
                {
                    throw new ArgumentException("ERROR: Min has to be lower than max!", nameof(min));
                }
                if (value is null)
                {
                    throw new ArgumentNullException("ERROR: Value cannot be null!", nameof(Value));
                }
            }

            Value = value;
            if (_value is null)
            {
                throw new NullReferenceException("Value remained nll after assignement!");
            }
        }
    }
0

There are 0 answers