суббота, 30 января 2016 г.

My tricky .NET interview question

At last interview i was asked the question: suppose you have two classes - base and derived, base class has virtual method and call it in constructor. Derived class overrides this virtual method and writes to console an argument, that was passed to its constructor. Then some hosting code creates instance of Derived and the question is: what will be written on the screen?

I think everyone was asked such question at least once. But i found very interesting approach to complicate this question. What if we define readonly field for derived class and write it to console to?
This is the starting code from my interview question:
 public class Base  
 {  
   public Base()  
   {  
     Init();  
   }  
   
   protected virtual void Init()  
   {  
       
   }  
 }  
   
 public class Derived : Base  
 {  
   private readonly string _arg;  
   
   public Derived(string arg)  
   {  
     _arg = arg;  
   }  
   
   protected override void Init()  
   {  
     Console.WriteLine(_arg ?? "<null>");  
   }  
 }  
Obviously the "<null>" will be written on the screen, This is the complicated code with readonly field _arg1:
 public class Derived : Base  
 {  
   private readonly string _arg;  
   private readonly string _arg1 = new string(new []{'a', 'b'});  
   
   public Derived(string arg)  
   {  
     _arg = arg;  
   }  
   
   protected override void Init()  
   {  
     Console.WriteLine(_arg ?? "<null>");  
     Console.WriteLine(_arg1 ?? "<null>");  
   }  
 }  
Do you know what will be written on the screen?
Ok, it will be:
 <null>  
 ab  
To successfully solve it you need to know, that execution order for constructors is from base to derived, but for initializers is vice versa. Eric Lippert has an explanation for this behaviour here.
So, we are ready for the new interviews :)

Комментариев нет:

Отправить комментарий