You cannot and should not, because it may not be a mistake. Consider an additional class:
class BarBase : IBase, IBar
{
}
Now:
IBase item = new BarBase();
IBar bar = item as IBar;
This will leave baras a non-zero reference - so why do you want this to be a compile-time error? Note that the compiler should not / should not take note:
- How did you actually initialize
item - Regardless of whether there are any classes that implement
IBaseandIBar
, . :
public sealed class Sealed {}
public interface IFoo {}
Sealed x = null;
IFoo foo = x as IFoo;
Sealed, IFoo, Sealed, ... .