I have some code that I have no control of. This code accepts an object parameter and attempts to cast it to a type known at compile time like this:
KnownType item = (KnownType) parameter;
Is it possible in C# to design a custom class MyClass
(not derived from KnownType) that can be passed as parameter to the above code and be converted to KnownType
by the above code, provided that MyClass
can convert itself to KnownType
using its member method:
protected KnownType ConvertToKnownType()
{
// conversion code goes here
}
I have tried to implement a custom conversion operator like this:
public static implicit operator KnownType(MyClass source)
{
KnownType result;
// conversion goes here
return result;
}
but it didn't work (it was not used). Am I right to assume that the cast operator only works when the source type, target type and conversion operators are known at compile time?
Edit: I initially didn't provide more details about the code doing the conversion because I think it is irrelevant and because I am mainly interested in the way the cast operator is implemented, i.e. does it take look at the runtime type to find an appropriate converter or is the decision made at compile time?
To clear things out, KnownType
is in fact DataRowView
, while MyClass
is a wrapper class for DataRowView
that has to derive from some other type. MyClass
keeps a reference to a DataRowView
. Instead of binding ComboBox.DataSource
to a DataView
, I bind it to an IList<MyClass>
but I still need the ComboBox
to be able to access the DataRowView
column values as if I was binding an IList<DataRowView>
. Unfortunately the cast operator works the way I was afraid it would: it only takes into account compile time type information to do conversions (it does however use runtime type information when casting between types in the same inheritance tree).
No, it is not possible. The cast provided would only succeed if you're able to derive your class from that class. Any type of conversion not based on inheritance would require the class performing the conversion to do something different than what it's doing.
Am I right to assume that the cast operator only works when the source type, target type and conversion operators are known at compile time?
Yes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With