Quote:
|
I have read in the book that object is the root of all classes and any variable which has type of object can be cast to any type.
|
I hink you misunderstood that somehow. The first part is true, but the second isn't. So, all objects inherit Object, and can be cast to an object. However, you cannot just cast any type to any other type. Consider these hierarchies:
Code:
Vehicle
Car
Truck
Animal
Goat
Cow
Now, a Cow is an animal, so something like this should work:
Code:
Cow clarabelle = new Cow();
Animal animal = (Animal) cow;
This casts the Cow type to a more generic Animal type.
But would you expect this to work:
Code:
Cow clarabelle = new Cow();
Truck truck = (Truck) cow;
In other words, as Sam said: "You can only 'cast' if the object is the type you are casting to or implements an implicit convertion operator (e.g. An int to a double.)" You can cast a
Cow to an Animal or to an Object (because ultimately a Cow IS an Animal and it IS an Object), but not to "any type" or arbitrary other types such as Trucks, Vehicles or ints.
Your code works because there are conversions between ints and chars available that, if I am not mistaken, call Convert.ToInt32 under the hood.
Cheers,
Imar