简体   繁体   中英

c# upcasting is always allowed

In Java ,

"Up-casting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException."

( What is the difference between up-casting and down-casting with respect to class variable )

Is upcasting also always allowed in C# ?

OOP principles state that you can always upcast; however, unlike Java with very restricted number of primitive classes , .Net implementation allows to declare struct types, some of them are weird counter-examples with boxing :

 TypedReference reference = new TypedReference();

 // Compile time error here! Even if Object is the base type for all types
 Object o = (Object)reference;

Technically, TypedReference is an Object :

 Object
   ValueType
     TypedReference

you can easily check it:

 Console.Write(typeof(TypedReference).BaseType.BaseType == typeof(Object) 
   ? "TypedReference derived from Object via ValueType" 
   : "Very strange");

but in order to be represented as Object instance (via cast) it should be boxed which can't be done.

Yes, it is allowed, since a subclass is a particularization of the ancestor class.

Example:

Let us consider the case when we have a class called Bird , another called Sparrow and a third one Eagle . Sparrow and Eagle are inherited from Bird . Sparrows differ from Eagles greatly, but they are Bird s. So, if you want to have a Collection of Bird s for some reason, then you can have Eagle and Sparrow objects in that Collection at the same time, since they are still Birds , if only specific Bird s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM