Click here to Skip to main content
13,297,547 members (49,551 online)
Click here to Skip to main content
Add your own
alternative version


57 bookmarked
Posted 14 Nov 2007

Real Self-Replicating Program

Rate this:
Please Sign up or sign in to vote.
A self-reproducing, mutable, compiling, and executing computer program.

Screenshot - SelfReplication.png


From Wiki:

Self-replication is any process by which a thing might make a copy of itself.


At one point, I wanted a small program to compile some Notepad edited scripts and run them on the fly. There is this nice project called "C# Script: The Missing Puzzle Piece". But, that is for professionals. And then, one night I went to do some coding. And came up with a code compiler. But, this was not enough. I wanted to store the source-code for this program into the program itself, and a final spec was to generate this same source code out of the program.

In short:

  1. There is only one executable.
  2. When starting the executable, it generates its own source code.
  3. When starting the executable again, it compiles this source code and executes it, showing the same user interface!

    A nice test is to delete the executable and compile the generated source code by using Visual Studio or the command line C# compiler:

    > del SelfReplication.exe
    > csc SelfReplication.cs
    > move SelfReplication.cs SelfReplication-old.cs
    > SelfReplication.exe
  4. The last statement generates a SelfReplication.cs file.
  5. The old and the new generated files are exactly the same!!

A feature of the program is you can change (mutate) the source code, adding new functionality and generating a totally new executable. The new program will be able to replicate itself, including your mutation, in the same way as the original one.

Using the code

The code has four sections:

The compiler

The compiler is a straightforward C# compiler which uses a file path to a C# file and produces an assembly of the source file. A nice feature is to get the names for the ReferencedAssemblies by calling GetReferencedAssemblies on the assembly itself.

private Assembly CompileCSharp(string strFilePath)
    if (strFilePath == null)
        return null;
    StreamReader sr = new StreamReader(strFilePath);
    string strSource = sr.ReadToEnd();
    CodeDomProvider cc = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters();
    foreach (AssemblyName assemblyName in 
        cp.ReferencedAssemblies.Add(assemblyName.Name + ".dll");
    cp.GenerateInMemory = true;
    CompilerResults cr = cc.CompileAssemblyFromSource(cp, strSource);

    StringBuilder sb = new StringBuilder();

    if (cr.Errors.HasErrors || cr.Errors.HasWarnings)
        foreach (CompilerError err in cr.Errors)
        MessageBox.Show(sb.ToString(), "Error", 
        return null;
    return cr.CompiledAssembly;

Compiling and executing an assembly

This function is also straightforward. It searches for any Main method on the compiled assembly, and invokes (executes) this Main method using the FilePath as an argument.

private void Execute(object FilePath)
    Assembly assembly = CompileCSharp(FilePath as string);
    if (assembly == null)

    foreach (Type t in assembly.GetTypes())
        MethodInfo info = t.GetMethod("Main",
            BindingFlags.Public |
            BindingFlags.NonPublic |

        if (info == null)

        object[] parameters = new object[]
        { new string[] { FilePath as string } };
        info.Invoke(null, parameters);

The main program

This is a tricky one. It checks for the existence of SeflReplication.cs. If it does not exist, it writes the contents of MYSELF to disk to clean up the code (not shown in this source listing for brevity). After writing it to disk, it is read back again and the MYSELF string is replaced by itself. It took me about 2 or 3 hours to get this right.

static class Program
    static void Main(string[] args)
        string strFilePath;
        if (args.Length == 0)
            string strDirectory =
            strFilePath = Path.Combine(strDirectory, "SelfReplication.cs");
            if (!File.Exists(strFilePath))
                StreamWriter sw = new StreamWriter(strFilePath);

                StreamReader sr = new StreamReader(strFilePath);
                string strCode = sr.ReadToEnd();

                int intI = strCode.IndexOf(" " + "MYSELF");
                if (intI > 0)
                    strCode = strCode.Substring(0, intI + 7) + 

                string strInsertCode = "MYSELF=@\"" + 
                       strCode.Replace("\"", "\"\"") + "\";";

                strCode = strCode.Replace("MYSELF" + ";", strInsertCode);

                sw = new StreamWriter(strFilePath);

            strFilePath = args[0];
        Application.Run(new SelfReplication(strFilePath));
    public static string MYSELF=@".......";

Now, the basics are in place. But in this era, there is not much place for Console programs, so I added a simple user interface to the program. You have to press a button for starting the replication (once). This prevents us from making some kind of runaway virus.

Adding a GUI

The GUI has a button on a small window. An event handler starts a new thread, having the FilePath as an argument. When the parent of all parents dies, it kills all the children.

private string strFilePath;
public SelfReplication(string strFilePath)
    this.strFilePath = strFilePath;
    this.button1 = new Button();
    this.button1.Location = new Point(75, 25);
    this.button1.Size = new Size(100, 25);
    this.button1.Text = "Replicate";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    this.ClientSize = new Size(250, 75);
    this.Text = "SelfReplication";

private void button1_Click(object sender, EventArgs e)
    Thread thread = new Thread(new ParameterizedThreadStart(Execute));
    thread.Name = "Execute";
    thread.IsBackground = true;

By writing this article, new ideas popped up. I am thinking of a contest to mutate the source-code, doing all kinds of weird stuff. There are only a few rules for this contest, which are mentioned in the head of this article.

Another idea is to compile to disk rather than compiling in-memory, leaving all other 'external' programs untouched.

Have fun with the program, and leave some comments when doing awful awesome things inspired by my article.

Points of interest

If you are interested in self-replication, you should definitely read the Wiki article about it.

And for this project, the Quin article will get you moving.


Thanks to Stewart Roberts for the Visual Basic .NET version of the program.


As of writing, the presented source code is version 1.0.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Alphons van der Heijden
Retired Van der Heijden Holding BV
Netherlands Netherlands
I'm Alphons van der Heijden, living in Lelystad, Netherlands, Europa, Earth. And currently I'm retiring from hard working ( ;- ), owning my own company. Because I'm full of energy, and a little to young to relax ...., I don't sit down, but create and recreate software solutions, that I like. Reinventing the wheel is my second nature. My interest is in the area of Internet technologies, .NET etc. I was there in 1992 when Mosaic came out, and from that point, my life changed dramatically, and so did the world, in fact. (Y)

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Kanasz Robert6-Nov-12 3:32
mvpKanasz Robert6-Nov-12 3:32 
Generalanother possible usage Pin
Roey C21-Nov-07 2:52
memberRoey C21-Nov-07 2:52 
GeneralRe: another possible usage Pin
dawmail33323-Dec-07 16:05
memberdawmail33323-Dec-07 16:05 
What like viruses?

Big Grin | :-D
GeneralRe: another possible usage Pin
Roey C24-Dec-07 6:33
memberRoey C24-Dec-07 6:33 
GeneralMalware source on CP Pin
jonty219-Nov-07 14:51
memberjonty219-Nov-07 14:51 
GeneralRe: Malware source on CP Pin
alphons20-Nov-07 12:03
memberalphons20-Nov-07 12:03 
GeneralVB Version Pin
Stewart Roberts18-Nov-07 14:35
memberStewart Roberts18-Nov-07 14:35 
GeneralRe: VB Version Pin
alphons18-Nov-07 15:36
memberalphons18-Nov-07 15:36 
QuestionRe: VB Version Pin
Stewart Roberts19-Nov-07 6:12
memberStewart Roberts19-Nov-07 6:12 
AnswerRe: VB Version [modified] Pin
alphons20-Nov-07 12:00
memberalphons20-Nov-07 12:00 
GeneralRe: VB Version Pin
Stewart Roberts20-Nov-07 13:46
memberStewart Roberts20-Nov-07 13:46 
GeneralRe: VB Version Pin
dawmail33323-Dec-07 16:20
memberdawmail33323-Dec-07 16:20 
GeneralRe: VB Version Pin
Stewart Roberts27-Dec-07 8:52
memberStewart Roberts27-Dec-07 8:52 
GeneralMutation Pin
Daniel Vaughan15-Nov-07 1:09
memberDaniel Vaughan15-Nov-07 1:09 
GeneralRe: Mutation Pin
alphons18-Nov-07 15:32
memberalphons18-Nov-07 15:32 
QuestionWhy in memory? Pin
Giorgi Dalakishvili14-Nov-07 10:25
memberGiorgi Dalakishvili14-Nov-07 10:25 
AnswerRe: Why in memory? Pin
alphons14-Nov-07 12:08
memberalphons14-Nov-07 12:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 20 Nov 2007
Article Copyright 2007 by Alphons van der Heijden
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid