Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why c# null can implicit convert to System.Nullable<T>, but can not a self defined Nullable<T> [duplicate]

Tags:

c#

.net

Why null can implicit convert to System.Nullable<T> like this:

int? val = null;

but self defined Nullable<T> (modified from .net reference source) cannot assign null, is there some compiler magic? Could anyone tell me more internal implimentation?

[Serializable]
public struct Nullable<T> where T : struct
{
    private bool hasValue;
    internal T value;

    public Nullable(T value)
    {
        this.value = value;
        this.hasValue = true;
    }

    public bool HasValue
    {
        get
        {
            return hasValue;
        }
    }

    public T Value
    {
        get
        {
            if (!HasValue)
            {
                throw new Exception();
            }
            return value;
        }
    }

    public T GetValueOrDefault()
    {
        return value;
    }

    public T GetValueOrDefault(T defaultValue)
    {
        return HasValue ? value : defaultValue;
    }

    public override bool Equals(object other)
    {
        if (!HasValue) return other == null;
        if (other == null) return false;
        return value.Equals(other);
    }

    public override int GetHashCode()
    {
        return HasValue ? value.GetHashCode() : 0;
    }

    public override string ToString()
    {
        return HasValue ? value.ToString() : "";
    }

    public static implicit operator Nullable<T>(T value)
    {
        return new Nullable<T>(value);
    }

    public static explicit operator T(Nullable<T> value)
    {
        return value.Value;
    }
}

test code below, compile error

Nullable<int> x = null; //ERROR Cannot convert null to 'Nullable<int>' because it is a non-nullable value type
like image 791
benlong Avatar asked Apr 11 '15 04:04

benlong


1 Answers

Section 6.1.5 of the C# 5.0 specification:

6.1.5 Null literal conversions
An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.

Note that this compiler-provided implicit conversion exists only to nullable types. Your custom-defined Nullable<T> is not a nullable type as defined by the C# specification. It's just some struct that you've declared that has a lot of the features of the built-in Nullable<T> type (described in the referenced section 4.1.10), but which is not in fact "nullable" per the definition in C#.

like image 82
Peter Duniho Avatar answered Oct 11 '22 18:10

Peter Duniho