This code raises an exception at run time because of an invalid cast : Object Cast « Class Interface « C# / C Sharp






This code raises an exception at run time because of an invalid cast

  

using System;


public class Starter {
    public static void Main() {
        MyClass obj = new MyClass();
        // Fails at compile time
        // YClass alias=obj;

        // Fails at run time
        YClass alias = (YClass)obj;

        obj.MethodA();
        obj.MethodB();

    }
}

public class MyClass {
    public virtual void MethodA() {
    }
    public virtual void MethodB() {
    }
}

public class YClass : MyClass {
    public override void MethodA() {
    }
}

   
  








Related examples in the same category

1.Casting Objects
2.Downcast will fail.
3.Casting objects: upcastCasting objects: upcast
4.Casting objects: downcastCasting objects: downcast
5.Variables of type object can accept values of any data type