Interface Cast Type Safety

Type safety prevents unwanted casting during compile-type. How can one achieve the same compile-time type safety for inherited interfaces?

public interface IBase { }
public interface IFoo : IBase { }
public interface IBar { }


public class Base { }
public class Foo : Base { }
public class Bar { }

public class Test
{
    public void TestInterface()
    {
        IBase item = null;

        IFoo foo = item as IFoo;

        // How to get an error?
        IBar bar = item as IBar;
    }

    public void TestClass()
    {
        Base item = null;

        Foo foo = item as Foo;

        // Error since Bar is not derived from Base
        Bar bar = item as Bar;
    }
}
Jon Skeet
people
quotationmark

You can't, and shouldn't - because it might not be an error. Consider an extra class:

class BarBase : IBase, IBar
{
}

Now:

IBase item = new BarBase();
IBar bar = item as IBar;

That will leave bar as a non-null reference - so why would you want it to be a compile-time error? Note that the compiler shouldn't/doesn't take notice of:

  • How you actually initialized item
  • Whether or not there happen to be any classes that implement IBase and IBar

It will take notice of whether such a conversion could ever be valid. Consider:

public sealed class Sealed {}
public interface IFoo {}

Sealed x = null;
IFoo foo = x as IFoo; // Error

Here there is no possible non-null value of Sealed that could implement IFoo, because there can't be any subclasses of Sealed implementing the interface... so the compiler gives an error.

people

See more on this question at Stackoverflow