Search code examples
c#casting

How to explicitly cast an object using the user-defined operator in the derived class


Consider the following code:

  class A {
    public static explicit operator int(A a) {
      Console.WriteLine("User-defined explicit cast A");
      return 42;
    }
  }
  
  class B : A {
    public static explicit operator int(B a) {
      Console.WriteLine("User-defined explicit cast B");
      return 1;
    }
  }

  public void TestCast() {
    A b = new B();
    Console.WriteLine($"The result is: {(int) b)}");
  }

This prints:

User-defined explicit cast A
The result is: 42

Is there a way for me to cast using the instance's type's user-defined cast operator at runtime, without knowing what the instance type actually is at compile time?


Solution

  • While overload resolution usually happens at compile time, casting the object to dynamic forces it to be resolved at runtime.

    class A {
        public static explicit operator int(A a) {
          Console.WriteLine("User-defined explicit cast A");
          return 42;
        }
      }
      
      class B : A {
        public static explicit operator int(B a) {
          Console.WriteLine("User-defined explicit cast B");
          return 1;
        }
      }
    
      public void TestCast() {
        A b = new B();
        Console.WriteLine($"The result is: {(int) (dynamic) b)}");
      }
    

    This now prints:

    User-defined explicit cast B
    The result is: 1