c# - Not throwing error in compile time when casting base to derived class -


this question has answer here:

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

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -