Reputation: 79
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
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
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 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.
Upvotes: 1
Reputation: 2099
yes, up-casting is allowed :-)
Casting and Type Conversions (C# Programming Guide)
Upvotes: 1