# Fibonacci Linq and UnitTests

Cristian Merighi () An article written under te pretext to associate a little bit of maths with some of the new features of the .Net Framework 3.5 and Visual Studio 2008 Pro.

I've always loved maths, I fell in love with programming.
Now I'm having some fun in putting them together!

Among the new features of the .Net Framework 3.5 you'll find - System.Linq namespace - the so-named extension methods: the idea is to plug new methods into existing framework objects (struct or classes doesn't matter)...

I think I lost control: I wrote plenty of them... extenders for numbers, strings, etc...
One of the most - maybe - unuseful methods I wrote is the implementation of an overloaded GetFibonacci() function... ^_^; ...which returns the n-th (where n is the contextual "extended" integer) of a given Fibonacci Sequence.
See the code below:

/// <summary>

/// Gets the n-th (zero-based) number of Fibonacci sequence (0, 1, 1, 2, 3, 5, 8...).

/// </summary>

/// <param name="number">The index of the Fibonacci sequence element.</param>

/// <returns>N-th integer of the sequence.</returns>

public static int GetFibonacci(this int number)

{

return number.GetFibonacci(0, 1);

}

/// <summary>

/// Gets the n-th (zero-based) number of a Fibonacci sequence based on particular seeds.

/// </summary>

/// <param name="number">The index of the Fibonacci sequence element.</param>

/// <param name="seed">Integer at the 0th position in the sequence</param>

/// <param name="seed">Integer at the 1st position in the sequence</param>

/// <returns>N-th integer of the sequence.</returns>

public static int GetFibonacci(this int number, int seed0, int seed1)

{

if (number == 0) return seed0;

if (number == 1) return seed1;

return (number - 1).GetFibonacci(seed0, seed1) + (number - 2).GetFibonacci(seed0, seed1);

}

The funny way of the whole thing was the TestUnit I wrote in order to test these extender methods:
as precise property of any Fibonacci sequence, the sum of 11 consecutive numbers equals the 7th number of this group multiplied by 11.
I think this is a pretty neat characteristic to test!

Right click and "create unit tests"... ...let's write relevant code...

/// <summary>

///A test for GetFibonacci

///</summary>

[TestMethod()]

public void GetFibonacciTest()

{

int n = 0;

for (int j = 0; j < 10; j++)

{

n += j.GetFibonacci(3, 4);

}

int expected = (6).GetFibonacci(3, 4);

Assert.AreEqual(11 * expected, n);

...Maths test is passed! ;) Take care. Bye.

feedback