Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamic conversion through cast operator

Tags:

c#

casting

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).

like image 928
P. Kouvarakis Avatar asked Sep 15 '16 13:09

P. Kouvarakis


1 Answers

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.

like image 105
Servy Avatar answered Oct 22 '22 18:10

Servy