c# - Not throwing error in compile time when casting base to derived class -
this question has answer here:
- compile-time , runtime casting c# 2 answers
you have these classes shown below:
public class { } public class b : { }
you cast base class type of derived class
a w = (b) new a(); b x = (b) new a();
this not work on run time because cannot convert base class derived class.
but why there no compile time error
? why visual studio allowed me reach run-time before throwing error?
there 2 types of casts
- once not allowed when classes have no common base , hence cast have no chance succeed. i.e. 'string' 'int'. such casts caught compiler , cause errors.
- casts have chance succeed - base derived have reasonable chance succeed. compiler allows such casts.
i believe reason why (b)new a()
allowed @ compile time if cast guaranteed fail because (b)someobjectoftypea
can succeed , new a()
1 of such "object of type a". compile time detection require additional infrastructure , not found beneficial (as cast fails @ runtime hence have low chance missed basic testing of code).
Comments
Post a Comment