Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting OOPS puzzle [closed]

Tags:

c#

oop

puzzle

Recently, I faced the below question in an interview. Initially I thought that the question was wrong, but the interviewer mentioned there is a solution for this. Given this class:

public class BaseHome {     public static void Main()     {         Console.WriteLine("A");     } } 

Write the following to the console:

B A C 

Rules:

  1. Do not change the Main function.
  2. Do not create any additional classes.

How can this be done?

like image 698
user3714387 Avatar asked Jun 06 '14 09:06

user3714387


2 Answers

Assuming you meant B A C on three lines (plus no typo on main method name):

namespace ConsoleApplication1 {     public class BaseHome     {         static BaseHome()         {             Console.WriteLine("B");              AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);         }          public static void Main()         {             Console.WriteLine("A");         }          private static void OnProcessExit(object sender, EventArgs e)         {             Console.WriteLine("C");             Console.Read();         }     } } 
like image 86
ken2k Avatar answered Oct 07 '22 22:10

ken2k


Hahaha, I figured it out. Create a static property!

public class BaseHome {     public static void Main()     {        Console.WriteLine("A");     }      public static BaseHome Console     {         get{ return new BaseHome(); }     }      public void WriteLine(string s) {         System.Console.WriteLine("BCA"); //Or multiple lines if you like     }  } 

Edit: Or, duh, just a field

public class BaseHome {     static BaseHome Console = new BaseHome();      public static void Main()     {        Console.WriteLine("A");     }      public void WriteLine(string s) {         System.Console.WriteLine("BCA"); //Or multiple lines if you like     }  } 
like image 34
Dennis_E Avatar answered Oct 07 '22 23:10

Dennis_E