When attempting to use the C# "as" keyword against a non-generic type that cannot be cast to, the compiler gives an error that the type cannot be converted.
However when using the "as" keyword against a generic type the compiler gives no error:
public class Foo { }
public class Bar<T> { }
public class Usage<T> {
public void Test() {
EventArgs args = new EventArgs();
var foo = args as Foo; // Compiler Error: cannot convert type
var bar = args as Bar<T>; // No compiler error
}
}
I discovered this behaviour in a much larger code base where the lack of a compile time error led to an issue at runtime.
Is the conflicting behaviour by design? If so, does anyone have any insight as to why?