If I create class A, and class B inherits from class A, why does C# require me to explicitly cast between them?
For example:
public class Mammal
{
}
public class Dog : Mammal
{
}
…
Mammal foo = new Dog(); // Invalid, wants an explicit cast
Mammal bar = (Mammal)new Dog(); // This one works
I’m just curious what the reasoning is behind that restriction.
Not quite sure what you mean? Both statements you have written compile and work fine.
Did you mean to write this as your question…?
If that was what you mean (which would match the comments) then the first one will not compile because a
Mammalis not aDogand the compiler knows it, so it won’t let you assign it (aDogis aMammalbecause it is derived from it, but the converse does not hold true). In the second one you’re overriding the compiler’s better judgement, and telling it you know better that aMammalreally is aDog, but as it isn’t, this statement will fail at runtime with anInvalidCastException.