C# Puzzle 1

person Thomas Levesquefolder_openPuzzleslocal_offer, access_time March 10, 2015

I love to solve C# puzzles; I think it’s a great way to gain a deep understanding of the language. And besides, it’s fun!

I just came up with this one:

static void Test(out int x, out int y)
    x = 42;
    y = 123;
    Console.WriteLine (x == y);

What do you think this code prints? Can you be sure? Post your answer in the comments!

I’ll try to post more puzzles in the future if I can come up with others.


    1. Thomas Levesque

      Usually, yes… but if that was the end of it, it wouldn’t be much of a puzzle 😉
      Hint: I can make this code print true without modifying the code of the Test method.

  1. Pingback: Dew Drop – March 10, 2015 (#1971) | Morning Dew

  2. It can print “true” if called with the same parameter, i.e. “Test(out A, out A)”.

    1. Thomas Levesque

      Exactly 😉

  3. Good idea, i like puzzles !
    This one was pretty basic.
    Waiting the next ones !

  4. When you pass the same reference (by using “out”), it will print true, otherwise it will print false.

    When x and y refer to the same variable it returns true.

    1. Thomas Levesque


  5. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1817

  6. It appears you can also change value of x in another thread…

    1. Thomas Levesque

      I guess it would be possible, but it can print true without using multiple threads

  7. Courtesy of Andy, a colleague of mine.

    If you override the Console output, you can get it to print true regardless of what you pass in.

        public class NotBoolTextWriter: TextWriter
            private readonly TextWriter console;
            public NotBoolTextWriter(TextWriter console)
                this.console = console;
            public override void WriteLine(bool value)
            public override Encoding Encoding
                get { return console.Encoding; }
        Console.SetOut(new NotBoolTextWriter(Console.Out));
        // Now call the 'Test' method.
    1. Thomas Levesque

      Oh, nicely done! Not what I had in mind, but very creative nonetheless 😉

    2. Thomas Levesque

      It will not always print true, though… it will just print the negation of the original condition.

  8. Pingback: Les liens de la semaine – Édition #125 | French Coding

  9. Pingback: Automate the Planet

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>