Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
    
do you mean void addOne(ref int a){a++;} –  shiona Jan 10 '13 at 21:18
    
That wouldn't compile. The ref keyword is not in the test (you would need addOne(ref a);). –  istepaniuk Jan 10 '13 at 21:22
    
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. –  CMP Jan 10 '13 at 22:11
4  
This isn't a very code golf friendly question. –  MrZander Jan 10 '13 at 22:36
    
@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. –  shiona Jan 10 '13 at 23:06

1 Answer 1

up vote 13 down vote accepted

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.

share|improve this answer
    
+1 for lateral thinking, but the question states "Implement an addOne function" I will clarify the Assert to make it pure mstest. –  istepaniuk Jan 11 '13 at 9:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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