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:
How can this be done?
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(); } } }
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With