I understand that a base class cannot be converted into a derived class. What I don't understand is why this isn't caught at compile time? For example:
class GradeBook
{
}
class ProfessorGradeBook : GradeBook
{
}
class Program
{
static void Main(string[] args)
{
ProfessorGradeBook a = (ProfessorGradeBook)new GradeBook();
//shouldn't this be a compile time error?
}
}
I've looked at other questions on stackoverflow but it still doesn't make sense to me why this would compile? ProfessorGradeBook a = (ProfessorGradeBook)new GradeBook();
would never succeed under any circumstance (right?) so why is this a run-time error instead of a compile-time error?
EDIT:
I already knew why the compiler would never catch this:
GradeBook a = new ProfessorGradeBook();
ProfessorGradeBook b = (ProfessorGradeBook)a;
At run-time, a
could be pointing to anything so the compiler should just trust you. I was more concerned with why the compiler would never catch this:
ProfessorGradeBook a = (ProfessorGradeBook)new GradeBook();
I guess the answer that makes the most sense is Eric Lippert's first comment, specifically "the vast majority of developers would never type that line of code" so the compiler team was never concerned with trying to make that an error.