Consider two simple classes
public class Parent
{
public void ShowData()
{
}
}
public class Child : Parent
{
public void GetData()
{
}
}
// Upcasting -- NO ERROR
Parent objParent = new Child();
// Downcasting -- ERROR
Child objChild = new Parent();
// Downcasting -- NO ERROR
Child objNewChild = (Child)new Parent();
UpCasting
does not require explicit casting
?DownCasting
requires explicit casting
?
Why UpCasting does not require explicit casting ?
Because it's always safe. It's never going to throw an exception.
Why DownCasting requires explicit casting ?
Because it's not safe. It can throw an exception, or lose information (e.g. casting from long
to int
in an unchecked context).
The compiler's happy to let you do safe things implicitly, but if you're going to do something "dangerous", you need to effectively tick the box saying "I know what I'm doing here."
From the C# spec, section 6.1:
The predefined implicit conversions always succeed and never cause exceptions to be thrown. Properly designed user-defined implicit conversions should exhibit these characteristics as well.
And section 6.2:
The explicit conversions that are not implicit conversions1 are conversions that cannot be proven to always succeed, conversions that are known to possibly lose information, and conversions across domains of types sufficiently different to merit explicit notation.
1 All implicit conversions are also explicit conversions. That's just a technical point to make bits of the spec simpler.
See more on this question at Stackoverflow