Towards the end of a course I was teaching last week, I gave my students an obfuscated programming challenge designed to test their understanding of several areas of both the CLR and C# that we'd been discussing throughout the course. In typical fashion, students had to predict the output of the program without the aid of any compilers - and they had to explain their answer to receive the prize.
However, I kept the code small enough to fit on a single projector screen, which prevented me from including a few things I had originally planned to test them on.
For your mental noodling enjoyment, the code below is the enhanced version of that challenge - unrestricted by screen space dimensions. Enjoy! (And remember - you can only use your eyes, brain and, if you like, a pencil and some paper.)
// Obfuscated CLR/C# 2.0 programming challenge. Predict the output of this program without
// using any compiler to build & run the code. Explain your answer.
//
// Mike Woodring
// http://www.bearcanyon.com
// Bear Canyon Consulting LLC
//
using System;
using IAR = System.IAsyncResult;
using IE1 = System.Collections.IEnumerable;
using IE2 = System.Collections.IEnumerator;
using MRE = System.Threading.ManualResetEvent;
using PTS = System.Threading.ParameterizedThreadStart;
class P
{
static void Main()
{
MRE fe = new MRE(false);
MRE pe = fe;
foreach( char c in new MSG() )
{
MRE ce = new MRE(false);
PTS m = delegate(object s) { P p = (P)s; p.W.WaitOne(); Console.Write(p.C); p.G.Set(); };
m.BeginInvoke(new P(c, pe, ce), delegate(IAR ar) { ((PTS)ar.AsyncState).EndInvoke(ar); }, m);
pe = ce;
}
fe.Set();
pe.WaitOne();
Console.WriteLine();
}
public P(char c, MRE w, MRE g) { C = c; W = w; G = g; }
char C;
MRE W;
MRE G;
class MSG : IE1
{
public IE2 GetEnumerator()
{
int i = 0;
foreach (char ch in new NTE<SM.B>()) yield return (i++ == 0 ? char.ToUpper(ch) : ch);
yield return (',');
yield return (' ');
foreach (char ch in new NTE<SM.A>()) yield return (ch);
yield return ('!');
}
}
class NTE<PT> : IE1
{
public IE2 GetEnumerator()
{
foreach (Type t in typeof(PT).GetNestedTypes()) { yield return t.Name[t.Name.Length - 1]; }
}
}
class SM
{
internal struct A
{
public struct cow { }
public class too { }
public interface car { }
public enum will { }
public struct pad { }
}
internal class B
{
public class wish { }
public struct see { }
public interface hill { }
public enum ball { }
public class boo { }
}
}
}
Posted
Sep 25 2006, 03:35 PM
by
mike-woodring