Tuesday, September 15, 2015

Lists and Arrays may be upcast to IEnumerable collections in C#!

Consider this:

using System.Collections.Generic;
namespace Whatever.Models
{
   public class Smasher
   {
      public string Smash(IEnumerable<int> numbers)
      {
         string concatenation = "";
         foreach (int number in numbers)
         {
            concatenation = concatenation + number;
         }
         return concatenation;
      }
   }
}

 
 

These two tests pass without the compiler freaking out:

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Whatever.Models;
namespace Whatever.Tests.Models
{
   [TestClass]
   public class SmasherTests
   {
      [TestMethod]
      public void TestWithArray()
      {
         
//arrange
         int[] numbers = new int[] { 13, 42 };
         Smasher smasher = new Smasher();
         
         
//act
         string feedback = smasher.Smash(numbers);
         
         
//assert
         Assert.AreEqual(feedback, "1342");
      }
      
      [TestMethod]
      public void TestWithList()
      {
         
//arrange
         List<int> numbers = new List<int>() { 13, 42 };
         Smasher smasher = new Smasher();
         
         
//act
         string feedback = smasher.Smash(numbers);
         
         
//assert
         Assert.AreEqual(feedback,"1342");
      }
   }
}

No comments:

Post a Comment