Mike Liu
Mike Liu

Reputation: 79

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#?

Upvotes: 1

Views: 191

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

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.

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 77063

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 Birds. So, if you want to have a Collection of Birds 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 Birds.

Upvotes: 1

cristallo
cristallo

Reputation: 2099

yes, up-casting is allowed :-)

Casting and Type Conversions (C# Programming Guide)

Upvotes: 1

Related Questions