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>
{
var d = t as D;
if (d != null)
d.M();
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)
{
if (t is D)
((D)t).M();
}
public static void M<T>(T t) where T : B
{
if (t is D)
((D)t).M();
}
}