CsWinRT icon indicating copy to clipboard operation
CsWinRT copied to clipboard

Runtime class projections should provide explicit cast operators from IInspectable

Open Scottj1s opened this issue 2 years ago • 0 comments

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'

Scottj1s avatar Aug 17 '21 20:08 Scottj1s