Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield return returning same result on each iteration

The problem is to generate combinations of search parameters to be used as test case inputs in automation tests.

public class CombinationInput<T> 
{
    public string Name { get; set; }
    public List<T> PossibleValues { get; set; }
    public bool ReadOnly { get; set; }
}

GetCombinations is a method in the Combinationsgenerator Class:

private IEnumerable<object[]> _GetCombinations(ArrayList inputs)
{
    var returnobjects = new object[inputs.Count];
    var element = inputs[0];
    var type = element.GetType();
    var generictype = type.GenericTypeArguments[0];
    var elementvalues = type.GetProperty("PossibleValues").GetValue(element, null) as IEnumerable;

    foreach (var val in elementvalues)
    {
        returnobjects[0] = val;
        if (inputs.Count > 1)
        {
            var objs = _GetCombinations(inputs.GetRange(1, inputs.Count - 1));
            foreach (var item in objs)
            {
                for (int i = 0; i < item.Length; i++)
                {
                    returnobjects[i + 1] = item[i];
                }
                yield return returnobjects;
            }
        }
        else
        {
            yield return returnobjects;
        }
    }
}

Inside TestMethod:

[TestMethod]
public void GetCombinationTest()
{
    var x = new CombinationInput<Enums.AmountType>();
    var y = new CombinationInput<Enums.AreaMeasureType>();
    var z = new CombinationInput<Enums.DisplayItemType>();

    ArrayList list = new ArrayList();
    list.Add(x);
    list.Add(y);
    list.Add(z);
    var combgen = new CombinationGenerator(list);
    var combs = combgen.GetCombinations();
}

Get Combinations is always returning the same combination when I run the code but when I debug through the code each time it hits the yield return statement its having the right combination.

like image 313
virali Avatar asked Apr 17 '26 21:04

virali


1 Answers

You always return the same object as you are editing the content itself. What you are yielding is the reference to an array, and it's always the same reference. Instead of reusing the same array, you should move the declaration and creation of returnobjects within the foreach loop.

like image 80
Simon Belanger Avatar answered Apr 19 '26 11:04

Simon Belanger