Sunday, November 21, 2010

A Quine With C#

A quine is a program, which prints it complete source code as output.
So for example, if the source code is

class Quine
{
    static void Main()
    {
        System.Console.WriteLine("This is no quine (yet).");
    }
}

The program had to output exactly this text. Depending on your experience in this topic, you will maybe find the task to write a quine as easy, hard or even impossible.
(For people interested in theory: It is guaranteed that quines exist in all "higher" programming languages, so for example, C, C#, Java etc. - since all these languages are Turing complete, and in Turing complete languages quines can be realised.)
If you start the problem naively, you could maybe suppose it is quickly solved. First you print the code until the line WriteLine(), then this line and finally the rest.
But hang on - we have to print the whole source code, including all WriteLine().
So if you write for example
string test = "abc";
and print this line via WriteLine()
WriteLine("string test = \"abc\";");
, in the next step this line has to be printed as well.
To avoid infinite recursion, the trick is to save the code in a string and then just print this string. Furthermore we also use, that in C# there are placeholders in the WriteLine() command which can be replaced later.
I now show the code of a quine written by me, the abstract requirements from above then hopefully get clear:

class Quine
{
    static void Main(string[] args)
    {
        string s = "class Quine {3} {0} {3} static void Main(string[] args) {3} {0} {3} string s = {2}{1}{2}; {3} System.Console.WriteLine(s, System.Convert.ToChar(123), s, System.Convert.ToChar(34), System.Environment.NewLine, System.Convert.ToChar(125)); {3} {4} {3} {4}";
        System.Console.WriteLine(s, System.Convert.ToChar(123), s, System.Convert.ToChar(34), System.Environment.NewLine, System.Convert.ToChar(125));
    }
}

No comments:

Post a Comment