Why is this character invalid when `x as Y` is working fine?

I stumbled upon this strange case yesterday, where it t as Dreturns a non-zero value, but (D)tcauses a compiler error.

Since I was in a hurry, I simply used t as Dand continued, but I wonder why the acts are invalid, as it treally is D. Can anyone shed some light on why the compiler doesn't like casts?

class Program
{
    public class B<T> where T : B<T> { }

    public class D : B<D> { public void M() { Console.Out.WriteLine("D.M called."); } }

    static void Main() { M(new D()); }

    public static void M<T>(T t) where T : B<T>
    {
        // Works as expected: prints "D.M called."
        var d = t as D;
        if (d != null)
            d.M();

        // Compiler error: "Cannot cast expression of type 'T' to type 'D'."
        // even though t really is a D!
        if (t is D)
            ((D)t).M();
    }
}

EDIT: , , . t B D. . # , ? , t D; ?

class Program2
{
    public class B { }

    public class D : B { public void M() { } }

    static void Main()
    {
        M(new D());
    }

    public static void M(B t)
    {
        // Works fine!
        if (t is D)
            ((D)t).M();
    }

    public static void M<T>(T t) where T : B
    {
        // Compile error!
        if (t is D)
            ((D)t).M();
    }
}
+5
3

((D)t).M();

((D)((B)t)).M();

B D, "-, B" D. ", B", A, , A : B.

, . , .

((D)t).M();       // potentially across, if t is an A
((D)((B)t)).M();  // first up the hierarchy, then back down

, ((D)((B)t)).M();, t D. ( is , .)

( , if (t is D).)

:

class Base { }
class A : Base { }
class C : Base { }

...
A a = new A();
C c1 = (C)a;         // compiler error
C c2 = (C)((Base)a); // no compiler error, but a runtime error (and a resharper warning)

// the same is true for 'as'
C c3 = a as C;           // compiler error
C c4 = (a as Base) as C; // no compiler error, but always evaluates to null (and a resharper warning)
+3

public static void M<T>(T t) where T : D

, , T D.

, T D T.

: List<int> to int

+1

, T B<T>.

, T T D, . T B<T>, D.

, , T D, . .. where T: B<T>, D where T: D, , T B<T>, .

: t as D, . , , , T D, .

. , . , ?

0

All Articles