Subject:

C# puzzles


Date: Message-Id: https://www.5snb.club/posts/2024/csharp-puzzles/

Two puzzles about funny C# behavior I discovered in the past.

The first one is fully defined, the second one is Quite Clever.

The goal is to make the program reach the return 0; line, through inserting code. (No, doing a Environment.Exit(0) is not the solution, it needs to reach the existing return 0).

You don’t need to do stuff like spawn the process again or patch a binary on-disk.

The code is compiled and has no warnings with mcs <filename>. mcs --version is 6.12.0.182. (Assume language version 7 or above).

Format Fun

Let’s start easy. Make this program say hi to me :)

public static class Program {
    public static int Main() {
        var goodbye = new global::System.Text.StringBuilder("Bye Bye");

        YourStuff.SecretSauce($"{goodbye}, 522");

        // Make this print "Hello, 522"
        System.Console.WriteLine($"{goodbye}, 522");

        if (goodbye.ToString() != "Hello") {
            System.Console.WriteLine("You have failed!");
            return 1;
        }

        return 0;
    }
}

public static class YourStuff {
    // XXX Write whatever SecretSauce function you need in order to make it work.
}
Hint Is a $"" always a string?

Answer: format-fun.cs

Double Fun

(Your solution here does not need to be cross platform. As long as it works on your machine. However, remember no unsafe!)

public static class Program {
    public static int Main() {
        var foo = new global::System.Text.StringBuilder("Bye Bye, ");
        var bar = new global::System.Text.StringBuilder("World?");

        YourStuff.SecretSauce(foo);

        System.Console.WriteLine(foo.ToString() + bar.ToString());
        // Make this print "Hello, World!"

        if (foo.ToString() == "Hello, " && bar.ToString() == "World!") {
            // These need to pass too!
            return 0;
        }

        System.Console.WriteLine("You have failed!");
        return 1;
    }
}

public static class YourStuff {
    // Write whatever you need here to make it work.
}
Hint Doing this isn't technically unsafe but it is definitely unsafe.

Answer: double-fun.cs