Search code examples
c#type-conversioninternals

C#: Writing an explicit cast operator for an internal class in another .NET assembly


I am dealing with a 3rd-party-library sealed internal type. Let's call this type VendorInternalTypeA. It is used in the assembly VendorLibraryA.

I want to substitute a different type, one of my own, for VendorInternalTypeA in the a couple of places. This works better than you might expect, but there is a sticking-place, also in 3rd-party internal code:

// Example code to illustrate the problem: no actual ArrayLists are being used.

void SaveA(object maybeA) {
   arrayList.Add(maybeA);
}

VendorInternalTypeA LoadA() {
   return (VendorInternalTypeA) arrayList[0];
}

What this means is that LoadA is expecting an instance of VendorInternalTypeA, or at least something that it can explicitly cast to VendorInternalTypeA. A subclass would work well here -- but VendorInternalTypeA is sealed, so I can't subclass it.

It occurred to me, after a bit of pondering, that if I could define a class that implemented an explicit operator for VendorInternalTypeA, that cast would work, and I'd be able to pass in instances of my own class and have them play nicely!

I got all excited, until I remembered that VendorInternalTypeA is also an internal class, so I can't reference it directly in my code.

So, my question to you: is there a way around this, with reflection, IL emission, or other slightly hacky approaches? A way to reference this internal class in the definition of another class?

(I am 90% to giving up on the project and saying it can't be done at all -- and still may, even if the answer is "yes, and here's how". But this is a really interesting question to me.)


Solution

  • No, there is not. Even if the class was public and you did have an explicit conversion to VendorInternalTypeA from your class, the code in question is casting an expression of type object to VendorInternalTypeA not an expression of your custom type, so the explicit conversion operator won't be used even if it exists.

    User defined conversion operators are bound at compile time when the compile time type of the expression being converted has a user defined operator to the type it's being converted to.