C# arbitrary cast

The following won't compile. It feels like it should. I'm wondering if there is a way around the problem. If possible, I'd prefer to avoid requiring anything to descend from class.

public static Func<DP, R> CastDomain<D, R, DP>(this Func<D, R> function) {
  return (DP dp) => {
    if (dp is D) {
      D d = (D)dp; // Compile error: cannot convert DP to D. But that's crazy as we are inside if (dp is D) {
      return function(d);
    } else {
      // handle the error . . .
    }
  };
}
Jon Skeet
people
quotationmark

// But that's crazy as we are inside if (dp is D)

That doesn't make any difference. There's nothing in the C# specification which says that the validity of a cast can depend on whether you've already checked something.

Basically, you can't convert between generic types like that - you'll have to go via object. It's annoying, but that's the way of things:

D d = (D) (object) dp;

people

See more on this question at Stackoverflow