Search code examples
c#.netgenericsnullable

Can not deal with IEnumerable<int?> in generic


I have a method to concatenate strings provided by int?.

public string ConcatenateNumber(IEnumerable<int?> myList)
{
    return myList
        .Distinct()
        .Aggregate(
            new StringBuilder(), 
            (current, next) => current.Append("'").Append(next))
        .ToString()
        .Substring(1);
}

Now I want to do unit test.

[TestMethod]
public void InputIntegers_Should_Be_Concatenated_When_Consider_Distinct()
{
    var myList = CreateEnumerable(1, 2, 2, 3);
    var logic = new MainLogic();
    var result = logic.ConcatenateNumber(myList);
    Assert.AreEqual("1'2'3", result);
}

public IEnumerable<T> CreateEnumerable<T>(params T[] items)
{
    if (items == null)
        yield break;

    foreach (T mitem in items)
        yield return mitem;
}

However I have the compile error.

C#: Unknown method ConcatenateNumber(System.Collections.Generic.IEnumerable) of ....

I think it is caused by nullable integer int?. But I am not sure how to fix it.


Solution

  • Explicitly pass the type as a nullable int.

    var myList = CreateEnumerable<int?>(1, 2, 2, 3);
    

    For example:

    using System;
    using System.Linq;              
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            var p = new Program();
    
            var list = p.CreateEnumerable<int?>(1, 2, 3, 4);
            p.DoWork(list);         
        }
    
        public void DoWork(IEnumerable<int?> enumerable)
        {
            enumerable.ToList().ForEach(x => 
            {
                Console.WriteLine(x);
            });
        }
    
        public IEnumerable<T> CreateEnumerable<T>(params T[] items)
        {
            if (items == null)
                yield break;
    
            foreach (T mitem in items)
                yield return mitem;
        }
    }