I don't know if I can explain this right, but I'll give it a try
anyway. I'll probably screw up some of the explanation...
Casting an object using the explicit operator is a compile-time
routine. So if you have an object of type string, that is a string at
compile-time, then the explicit operator will work, and it will
generate a new MyCar object.
Casting a MyCar object that has been boxed into an object works
because the object really is a MyCar. You're not using one of the
operators to cast it, but rather the standard unboxing routine.
If you have a string or an int that has been boxed into an object, the
compiler doesn't treat them as string or int when choosing an
operator, and instead tries to unbox it as if it was a MyCar, and
fails because it's not a MyCar.
There are probably several ways of making this work, but off the top
of my head, the following should work in your GetMyCar method - this
will accept an object, but the actual type of that object can be
MyCar, int, or string. You'd handle each possibility, and cast it
first to the type that it really is, followed by casting that strongly-
typed int or string into MyCar.
static MyCar GetMyCar(object obj) {
if (obj is MyCar) {
return (MyCar)obj;
} else if (obj is string) {
return (MyCar)((string)obj);
} else if (obj is int) {
return (MyCar)((int)obj);
}
return null;
}
I'm sure there's a better way, but if your real-life scenario is as
simple as this, then this might work for you.
On Apr 29, 12:56 pm, Media8Slayer <[email protected]> wrote:
> I have a strange problem with unboxing.
>
> Take this code:
>
> static void Main(string[] args)
> {
> string carName = "Honda";
> object carObj = carName; // carObj is of type
> object with carName boxed
>
> MyCar theCar = (MyCar)carObj; // Invalid cast
>
> MyCar theCar2 = (MyCar)carName; // Works !
>
> MyCar theCar3 = (MyCar)(string)carObj; // Works
>
> MyCar theCar4 = GetMyCar((object)1); // invalid cast
> MyCar theCar5 = GetMyCar(carObj); // invalid cast
> MyCar theCar6 = GetMyCar(carName); // invalid cast
> }
>
> public class MyCar
> {
> public string Name;
>
> public MyCar(string name) { this.Name = name; }
>
> public MyCar(int carNbr) { if (carNbr==1)
> this.Name="Honda"; else this.Name="Unknown"; }
>
> public static explicit operator MyCar(string value)
> {
> return new MyCar(value);
> }
>
> public static explicit operator MyCar(int value)
> {
> return new MyCar(value);
> }
> }
>
> private static MyCar GetMyCar(object car) // car is a boxed
> string
> {
> return (MyCar)car; // does not work
> }
>
> So can I get the function GetMyCar to return properly if the car type
> is a string or integer?
>
> Anyone have any ideas?