C# Puzzlers: Elvis Lives

I was a Java instructor earlier in my career. The best thing about being a Java instructor is you really learn Java. I knew Java as well or better than anybody while I was teaching. I quickly learned that students ask the best questions and they forced me to truly understand Java.A group of developers, at work, started exploring Java Puzzlers. Java Puzzlers reminded me about how well I knew Java and how I don’t have the same depth of knowledge in C#. I want/need the same depth of knowledge in C# as I do in Java.I am currently working my way through the Java puzzlers in C#. This post is the result of the first puzzler. This puzzler was written by Jeff Grigg.Given the following: What will be printed to the console?

public class Elvis : King{    public bool IsAlive = true;    protected override void Kill()    {        IsAlive = false;        Console.WriteLine("The king is dead.");    }    public static void Main(String[] args)    {        Elvis elvis = new Elvis();        if (elvis.IsAlive)            Console.WriteLine("Long live the king!");        Console.WriteLine("Hit enter to continue....");        Console.ReadLine();    }}public abstract class King{    public King()    {        Kill();    }    protected abstract void Kill();}

It turns out it only prints

The king is dead.

This went against my instinct. Why? The same puzzler prints

The king is dead.Long live the king!

in Java. Java does not execute public bool IsAlive = true; until after the super constructor executes.This obviously does not happen in C#. C# must initialize all member variables before executing the constructor. This behavior seems to be more obvious than the Java behavior. I guess I should try not to think so hard when I am working through these puzzles ;)The code for the puzzlers can be found in my svn repository.https://esterline.devguard.com/svn/code/csharp_puzzlers

Advertisements

2 Responses

  1. […] finde ich auch den Ansatz von Adam Esterline nach C# Puzzlers (1, 2) ähnlich zu den Java Puzzlers zu suchen. Allerdings glaube ich nicht, dass die direkte […]

  2. “The king is dead.”
    “Hit enter to continue….”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: