So the other day I was just experamenting with some code, just for fun, and I ran into some difficulties. So I suppose my question is why the following code does not write to the original bigints array. I am sure I am doing something dumb, but please bear with me. I made my own simple "state machine" thinking that I could return what is essentially a reference to the value in the array, and get away with only two BigIntegers being in memory at any given time. What seems to be happening though is that the value of the BigInteger is copied and then the copy is returned. I thought that whenever you did this "SomeObj obj = new SomeObj();" the left hand side was essentially a really safe pointer. Now this code is really convoluted, so as you can see I was just messing around, and wouldn't use this anywhere else. Perhaps when I access "array[current]" in the getCurrent() method the array copies the datatype instead? I know I am being too clever for my own good, be gentle. Are BigInts value types?
/*Author: overwraith*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace Fibonacci {
class Program {
static void Main(string[] args) {
BigInteger[] bigints = new BigInteger[2] { new BigInteger(1), new BigInteger(2) };
try{
LoopingStateMachine<BigInteger> enumerable1 = new LoopingStateMachine<BigInteger>(bigints);
//advance one on second state machine
LoopingStateMachine<BigInteger> enumerable2 = new LoopingStateMachine<BigInteger>(bigints);
enumerable2.MoveNext();
while(enumerable1.MoveNext() && enumerable2.MoveNext()){
BigInteger current = enumerable1.getCurrent();
current += enumerable2.getCurrent();
Console.WriteLine("Fibonacci Number: " + current);
}//end loop
}catch(OutOfMemoryException){
//can't go any higher
}
Console.Write("Press any key to continue... ");
Console.ReadLine();
}//end main
}//end class
public class LoopingStateMachine<T> {
T[] array;
UInt32 current = 0;
public LoopingStateMachine(T[] arr){
array = arr;
}//end method
public T getCurrent(){
return array[current];
}
public bool MoveNext(){
//reset the current index
if (current == array.Length - 1)
current = 0;
else
this.current++;
return true;
}//end method
}//end class
}//end namespace