diff --git a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs index c261036c6b..e7f68e4f69 100644 --- a/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs +++ b/dotnet/src/Microsoft.Agents.AI.Workflows/WorkflowBuilderExtensions.cs @@ -128,9 +128,16 @@ public static class WorkflowBuilderExtensions Throw.IfNull(targets); List targetList = []; - int targetIndex = 0; - foreach (ExecutorBinding? target in targets) + using IEnumerator targetEnumerator = targets.GetEnumerator(); + if (!targetEnumerator.MoveNext()) { + throw new ArgumentException("Targets collection cannot be empty.", nameof(targets)); + } + + int targetIndex = 0; + do + { + ExecutorBinding? target = targetEnumerator.Current; if (target is null) { throw new ArgumentNullException(nameof(targets), $"Targets collection contains a null element at index {targetIndex}."); @@ -139,8 +146,8 @@ public static class WorkflowBuilderExtensions targetList.Add(target); targetIndex++; } + while (targetEnumerator.MoveNext()); - Throw.IfNullOrEmpty(targetList, nameof(targets)); return targetList; } diff --git a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowBuilderSmokeTests.cs b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowBuilderSmokeTests.cs index 27bbb1092c..4e9cb19ee3 100644 --- a/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowBuilderSmokeTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.Workflows.UnitTests/WorkflowBuilderSmokeTests.cs @@ -396,6 +396,7 @@ public partial class WorkflowBuilderSmokeTests WorkflowBuilder builder = new("start"); NoOpExecutor source = new("start"); NoOpExecutor target = new("target"); + NoOpExecutor otherTarget = new("other-target"); // Act/Assert Assert.Throws("builder", () => ((WorkflowBuilder)null!).AddChain(source, [target])); @@ -403,6 +404,7 @@ public partial class WorkflowBuilderSmokeTests Assert.Throws("executors", () => builder.AddChain(source, null!)); Assert.Throws("executors", () => builder.AddChain(source, [target, null!])); Assert.Throws("executors", () => builder.AddChain(source, [target, source])); + Assert.Throws("executors", () => builder.AddChain(source, [target, otherTarget, target])); } [Fact]