2
\$\begingroup\$

Given the following test, implement an addOne function in C# so it passes, without any modification to the test. TIP: Yes, it is possible.

[TestMethod]
public void TheChallenge()
{
    int a = 1;

    addOne(a);

    Assert.IsTrue(a == 2);
}

EDIT: clarified the Assert to avoid confusion. The value of a should be 2; there's no trick there.

\$\endgroup\$
7
  • \$\begingroup\$ do you mean void addOne(ref int a){a++;} \$\endgroup\$
    – shiona
    Commented Jan 10, 2013 at 21:18
  • \$\begingroup\$ That wouldn't compile. The ref keyword is not in the test (you would need addOne(ref a);). \$\endgroup\$
    – istepaniuk
    Commented Jan 10, 2013 at 21:22
  • \$\begingroup\$ Perhaps you could use reflection to somehow rewrite the IL for the test method to increment a after the return. That's all I can think of. \$\endgroup\$
    – captncraig
    Commented Jan 10, 2013 at 22:11
  • 4
    \$\begingroup\$ This isn't a very code golf friendly question. \$\endgroup\$
    – MrZander
    Commented Jan 10, 2013 at 22:36
  • \$\begingroup\$ @istepaniuk oh, I've never actually written any C#, so I googled and tried to understand the syntax for pass by reference. MrZander: it isn't tagged code golf. It's awfully simple for puzzle though. \$\endgroup\$
    – shiona
    Commented Jan 10, 2013 at 23:06

1 Answer 1

14
\$\begingroup\$

Ummm, simply provide an implementation of AssertTrue that doesn't throw anything?

void addOne(int a){}

void AssertTrue(bool b) { }

You never specified what testing framework is used here. It looks like MSTest, but I fired up a new test project and AssertTrue doesn't exist, so I took the liberty of implementing it myself.

EDIT

This solution might be what you were fishing for:

void addOne(int x)
{
  unsafe
  {
    int* i = &x;
    i += 4;
    *i += 1;
  }
}

I feels pretty fragile, but it works on my box consistently. It probably depends heavily on the compiler, so hopefully it is reproducible elsewhere.

\$\endgroup\$
1
  • \$\begingroup\$ +1 for lateral thinking, but the question states "Implement an addOne function" I will clarify the Assert to make it pure mstest. \$\endgroup\$
    – istepaniuk
    Commented Jan 11, 2013 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.