explicit operator for a cast

J

John Richardson

How does a custom casting operator work? I have a class that defines one,
but doesn't work as expected (or perhaps, the way I want it to).

I have the following example classes:
------------------
public class One : IOne {
....
}//One

public class Two {
public One MyOne;

....

public static explicit operator One (Two value) {
return value.MyOne;
}
}//Two
------------------

Now, I have an ArrayList that I would like to do the following, but it
doesn't work:
-------------------
ArrayList arrOfTwoObjects;
for (int x = 0....) {
IOne obj = arrOfTwoObjects[x] as IOne; //this cast fails, and obj is
null
}
-------------------

Throughout my code, I have the above handling with an arraylist, casting to
an interface. I'm not allowed to have an explicit cast operator to an
interface. Is the only solution to have Two implement IOne as well, and
delegate all the implementation to the child MyOne object? That is going to
be pretty cumbersome... :(

J
 
N

Nicholas Paldino [.NET/C# MVP]

John,

This happens because the array list returns an object, and the compiler
doesn't know how to cast from object to IOne. However, you can cast to a
Two instance, which knows how to cast to IOne, like so:

IOne obj = (One)(Two) arrofTwoObjects[x];

Hope this helps.
 
?

=?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?=

John said:
How does a custom casting operator work? I have a class that defines one,
but doesn't work as expected (or perhaps, the way I want it to).

public static explicit operator One (Two value) {
return value.MyOne;

for (int x = 0....) {
IOne obj = arrOfTwoObjects[x] as IOne; //this cast fails, and obj is
null

<snip>

"as" will never do user defined conversions, only reference conversions
(direct class hierarchy conversions) or boxing operations.

To take advantage of such typecasting operators that you used you must
use a normal typecast, ie. IOne obj = (IOne)twoObject;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top