CsWinRT
CsWinRT copied to clipboard
Runtime class projections should provide explicit cast operators from IInspectable
Some API designs use type erasure for returned objects, such as event args.
Callers are then expected to discover what type the object is and cast accordingly. If the object has implemented IInspectable.GetRuntimeClassName correctly, the dynamic type of the object will permit downcasting:
var args = (SomeEventArgType)eventArg; // works if eventArg is an IInspectable that reports "SomeEventArgType" for GetRuntimeClassName
If not, the downcast will fail and the caller will instead have to construct an instance of the downcast type as follows:
var args = SomeEventArgType.FromAbi(((IInspectable)eventArg).ThisPtr);
The dev experience could be improved here a bit if SomeEventArgType provided a cast operator:
public static explicit operator SomeEventArgType(IInspectable insp) => FromAbi(insp.ThisPtr);
so that this is possible:
var arg = (SomeEventArgType)(IInspectable)eventArg;
Unfortunately, the intermediate cast to IInspectable is necessary as it is not possible to define a cast operator from 'object'