Casting

You might need to a cast an instance of a type argument. Because type arguments are implicitly System.Object types, the instance can always be cast to that type. In addition, the instance also can be cast to a derivation constraint because the type argument is related to the constraint, and therefore a safe cast is assured. Finally, an instance of a type argument can be cast to any interface even if the interface is not listed as an interface constraint. Because there is no restriction on casting to interfaces, it is not type-safe. For that reason, care should be taken to ensure that you appropriately cast to an implemented interface.

In the following code, ZClass is a generic type. It has a single type parameter (T) that has three constraints: YClass type derivation, IA interface derivation, and the default constructor constraint. An instance of the T parameter is created in the method called Cast. The instance is then cast in succession to the YClass class and then the IA and IB interfaces. The first two casts work as expected. The third cast fails only at run time. The type parameter is not related to IB. However, the compiler does not notice. Therefore, an exception is raised at run time, which is the worst possible scenario and underscores the type-unsafe nature of casting an instance of a type argument to an interface:

public class ZClass<T> where T : YClass, IA, new() {
    static public void Cast() {
        T obj = new T();
        ((YClass) obj).MethodA();
        ((IA) obj).MethodA();
        ((IB) obj).MethodB();     // runtime error
    }
}

public class YClass : IA {
    public void MethodA() {
        Console.WriteLine("YClass.MethodA");
    }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.46.78