C # Incorrect understanding of <T> request - warning "always always true"

I am amused by writing the Select and SelectMany options for the type Nullable<T>in C # (including the syntax for understanding the LINQ query. When I write some test queries, the compiler gives me a warning:

public static void Test()
{
    var z1 =
        from x in 5.Nullable()
        from y in 6.Nullable()
        select x + y;

    var z2 =
        from x in 3.Nullable()
        from y in default(DateTime?)
        select y.Month == x;

    var result =
        from x in z1
        from y in z2
        select x == 11 && !y;

    Console.WriteLine(result.HasValue // <-- this expression is "always true"
        ? result.Value.ToString()
        : "computation failed");
}

How can he say this? I know that this is not an interpretation of the requests above, because if I change the code, so HasValue MUST be false (for example, changing x in z1 to 20), it still gives a warning. Is this a mistake in the compiler or did I make a mistake?

I believe my method implementations are correct, but here they are for reference:

public static T? Nullable<T>(this T x)
    where T : struct 
{
    return x;
}

public static U? Select<T, U>(this T? n, Func<T, U> f)
    where T : struct
    where U : struct
{
    return n.HasValue
        ? f(n.Value)
        : default(U?);
}

public static U? SelectMany<T, U>(this T? n, Func<T, U?> f)
    where T : struct
    where U : struct
{
    return n.HasValue
        ? f(n.Value)
        : default(U?);
}

public static V? SelectMany<T, U, V>(this T? n, Func<T, U?> f, Func<T, U, V> g)
    where T : struct
    where U : struct
    where V : struct
{
    if (!n.HasValue) return default(V?);

    var u = f(n.Value);
    return u.HasValue
        ? g(n.Value, u.Value)
        : default(V?);
}
+4
source share
1 answer

ReSharper . :

var z1 =
    from x in default(int?)
    from y in 6.Nullable()
    select x + y;

if (z1.HasValue)
{
}

ReSharper "always true":

enter image description here

, false:

enter image description here

, ReSharper.


( OP .)

+3

All Articles