views:

245

answers:

2

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.

+5  A: 

Not quite sure what you mean? Both statements you have written compile and work fine.

Did you mean to write this as your question...?

Dog foo = new Mammal(); // Invalid, wants an explicit cast
Dog bar = (Dog)new Mammal(); // This one works

If that was what you mean (which would match the comments) then the first one will not compile because a Mammal is not a Dog and the compiler knows it, so it won't let you assign it (a Dog is a Mammal because 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 a Mammal really is a Dog, but as it isn't, this statement will fail at runtime with an InvalidCastException.

Greg Beech
And that would be a variance issue. http://blogs.msdn.com/ericlippert/archive/tags/Covariance%20and%20Contravariance/default.aspx
NickLarsen
It's not a variance issue.
itowlson
I was sure I had observed this before, but yes it appears my test code had the classes backwards
Kevin Laity
Correct; this is not a variance issue. For it to be a variance issue there has to be something like a generic type, array, method group conversion, and so on.
Eric Lippert
+2  A: 

They both work.

Keith Rousseau