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?

Reply via email to