Writing Self-Replicating Code in C#

C# has some fun features under its hood, like its ability to compile an assembly from source code dynamically at run-time, allowing you to do things like write self-replicating code, code that learns (or artificial intelligence), and so forth, to whatever degree of metamorphic and polymorphic behavior you desire to get out of it.

Take this console application, for example. In each iteration, it rewrites itself under a new pseudonym and modifies its own source code every time it re-runs itself:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Replicator
{
    class Program
    {

        static int iteration = 0;
        static string sourcePath = "../../Program.cs";

        static void Main(string[] args)
        {
            Console.WriteLine("Iteration: {0}.", iteration);
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters(new[] { "System.dll", "System.Core.dll", "Microsoft.CSharp.dll", "System.Linq.dll" }, String.Format("Replicator{0}.exe", iteration.ToString()), true);
            parameters.GenerateExecutable = true;
            string sourceCode = File.ReadAllText(sourcePath);
            sourceCode = sourceCode.Replace(String.Format("static int iteration = {0};", iteration.ToString()), String.Format("static int iteration = {0};", (iteration + 1).ToString()));
            File.WriteAllText(sourcePath, sourceCode);
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, sourceCode);
            if (results.Errors.HasErrors)
            {
                Console.WriteLine("A clone was not created. Fix your compile errors and try running this application again at a later time. Press any key to exit.");
                results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("A clone has been created. Press any key to run it.");
                Console.ReadLine();
                Process.Start(String.Format("Replicator{0}.exe", iteration.ToString()));
            }
        }
    }
}

Alexandru

"To avoid criticism, say nothing, do nothing, be nothing." - Aristotle

"It is wise to direct your anger towards problems - not people; to focus your energies on answers - not excuses." - William Arthur Ward

"Science does not know its debt to imagination." - Ralph Waldo Emerson

"Money was never a big motivation for me, except as a way to keep score. The real excitement is playing the game." - Donald Trump

"All our dreams can come true, if we have the courage to pursue them." - Walt Disney

"Mitch flashes back to a basketball game held in the Brandeis University gymnasium in 1979. The team is doing well and chants, 'We're number one!' Morrie stands and shouts, 'What's wrong with being number two?' The students fall silent." - Tuesdays with Morrie

I'm not entirely sure what makes me successful in general programming or development, but to any newcomers to this blood-sport, my best guess would be that success in programming comes from some strange combination of interest, persistence, patience, instincts (for example, someone might tell you that something can't be done, or that it can't be done a certain way, but you just know that can't be true, or you look at a piece of code and know something doesn't seem right with it at first glance, but you can't quite put your finger on it until you think it through some more), fearlessness of tinkering, and an ability to take advice because you should be humble. Its okay to be wrong or to have a bad approach, realize it, and try to find a better one, and even better to be wrong and find a better approach to solve something than to have had a bad approach to begin with. I hope that whatever fragments of information I sprinkle across here help those who hit the same roadblocks.

Leave a Reply

Your email address will not be published. Required fields are marked *