How to Route a Microsoft Agent Framework Workflow with a Switch in C#
A switch in a Microsoft Agent Framework workflow sends each message down exactly one of several paths: to the first case whose test is true, or to the default when no test is. This guide routes orders by their total, so a free order is rejected, a large one waits for a manager, and the rest are shipped.
Syntax
<builder>.AddSwitch(<source>, switchBuilder => switchBuilder
.AddCase<<T>>(<test>, <executor>)
.AddCase<<T>>(<test>, <executor>)
.WithDefault(<executor>));
| Part | What it is |
|---|---|
<builder> | The WorkflowBuilder that builds the workflow. AddSwitch returns it, so you can go on adding to it. |
<source> | The executor whose result is routed, documented as The source executor that determines the branching condition for the switch. |
switchBuilder | The SwitchBuilder that collects the cases. |
<T> | The type of the message <source> sends, which each test receives. |
<test> | A function that decides whether this case takes the message: The function receives an input object and returns true to select the case, and false otherwise. |
<executor> in AddCase | Where the message goes when the test is true. A case can name more than one executor: Each executor will be invoked if the predicate matches. |
WithDefault(<executor>) | Adds one or more executors to be used as the default case when no other predicates match. |
The order of the cases matters. The documentation of AddCase says Cases are evaluated in the order they are added. Microsoft's Edges guide adds that they're evaluated sequentially, stopping at the first match, so a message goes to the first case whose test is true, and to the default only when none is.
The Example
A console app called OrderRouter prices an order, then sends it down one of three paths. An order whose total is 0 is rejected, an order of 1,000 or more needs a manager's approval, and every other order is shipped. Each step is a plain C# function turned into an executor. Three orders go through the same workflow, one after another: pens, a laptop and a free sample. There's no AI model in it, so you don't need an Azure account.
Prerequisites
- The .NET 10 SDK.
dotnet --versionprints a version that starts with10.0.
Step 1: Create a Console App and Add the Workflows Package
In a terminal, in the folder where you keep your projects, create the app and move into it:
dotnet new console -o OrderRouter
cd OrderRouter
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/OrderRouter/OrderRouter.csproj:
Restore succeeded.
Then add Agent Framework's workflows package:
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/codesignctl.pem'.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/timestampctl.pem'.
info : Adding PackageReference for package 'Microsoft.Agents.AI.Workflows' into project '/Users/you/source/OrderRouter/OrderRouter.csproj'.
info : Restoring packages for /Users/you/source/OrderRouter/OrderRouter.csproj...
info : CACHE https://api.nuget.org/v3/vulnerabilities/index.json
info : CACHE https://api.nuget.org/v3-vulnerabilities/2026.11.20.05.34.20/vulnerability.base.json
info : CACHE https://api.nuget.org/v3-vulnerabilities/2026.11.20.05.34.20/2026.11.30.11.35.26/vulnerability.update.json
info : Package 'Microsoft.Agents.AI.Workflows' is compatible with all the specified frameworks in project '/Users/you/source/OrderRouter/OrderRouter.csproj'.
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/OrderRouter/OrderRouter.csproj'.
info : Generating MSBuild file /Users/you/source/OrderRouter/obj/OrderRouter.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/OrderRouter/obj/project.assets.json
log : Restored /Users/you/source/OrderRouter/OrderRouter.csproj (in 780 ms).
Microsoft.Agents.AI.Workflows has the workflow builder, the switch and the code that runs a workflow, and --version keeps you on the version this guide used. That's the only package this example needs: its steps are functions, not classes with [MessageHandler] methods, so it doesn't use the workflows source generator.
Step 2: Write the Steps as Functions
Replace everything in Program.cs with:
using Microsoft.Agents.AI.Workflows;
// The steps, as plain C# functions turned into executors.
Func<Order, PricedOrder> price = order => new PricedOrder(order.Item, order.Quantity * order.UnitPrice);
Func<PricedOrder, string> reject = order => $"{order.Item}: rejected, the total is 0.";
Func<PricedOrder, string> approve = order => $"{order.Item}: {order.Total:0.00} needs a manager's approval.";
Func<PricedOrder, string> ship = order => $"{order.Item}: {order.Total:0.00}, shipped.";
ExecutorBinding priceOrder = price.BindAsExecutor("PriceOrder");
ExecutorBinding rejectOrder = reject.BindAsExecutor("RejectOrder");
ExecutorBinding managerApproval = approve.BindAsExecutor("ManagerApproval");
ExecutorBinding shipOrder = ship.BindAsExecutor("ShipOrder");
And add the two records the steps use at the end of the file:
record Order(string Item, int Quantity, decimal UnitPrice);
record PricedOrder(string Item, decimal Total);
Orderis what comes in: an item, how many of it, and the price of one.PricedOrderis what the pricing step sends on: the item and its total.pricemultiplies the quantity by the unit price.reject,approveandshipeach turn a priced order into a line of text, where:0.00writes the total with two decimals.BindAsExecutor("PriceOrder")turns a function into an executor with that id. Its documentation: Configures a function-based message handler as an executor with the specified identifier and options. The function's parameter is the message the executor accepts, and what it returns is the message it sends on.
Step 3: Add the Switch
Add the workflow below the four ExecutorBinding lines:
Workflow workflow = new WorkflowBuilder(priceOrder)
// One path per order: the first case that matches wins, and the default takes the rest.
.AddSwitch(priceOrder, paths => paths
.AddCase<PricedOrder>(order => order?.Total == 0, rejectOrder)
.AddCase<PricedOrder>(order => order?.Total >= 1000, managerApproval)
.WithDefault(shipOrder))
.WithOutputFrom(rejectOrder, managerApproval, shipOrder)
.Build();
new WorkflowBuilder(priceOrder)starts the workflow atPriceOrder, which receives each order.AddSwitch(priceOrder, paths => ...)routes whatPriceOrdersends.pathsis the switch builder that the cases are added to.- The first
AddCase<PricedOrder>sends an order whose total is 0 toRejectOrder, and the second sends an order of 1,000 or more toManagerApproval. Each test receives thePricedOrder. The?.inorder?.Totalreads the total only when there is an order, so a test isfalsefor a missing one instead of throwing. WithDefault(shipOrder)sends every order that no case took toShipOrder.WithOutputFrom(rejectOrder, managerApproval, shipOrder)makes all three ends of the switch outputs of the workflow, so whichever path an order takes, its line of text is the output.
Step 4: Run Three Orders
Add this below the workflow:
Order[] orders =
[
new("Pens", 3, 2.50m),
new("Laptop", 1, 1250m),
new("Free sample", 0, 9.99m),
];
foreach (Order order in orders)
{
await using Run run = await InProcessExecution.RunAsync(workflow, order);
foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
if (workflowEvent is WorkflowOutputEvent output)
{
Console.WriteLine($"{output.ExecutorId,-16}{output.Data}");
}
}
}
ordersholds three orders: 3 pens at 2.50, 1 laptop at 1,250, and a free sample with a quantity of 0. Themafter a number makes it adecimal, the type ofUnitPrice.- The loop runs the same workflow once for each order, one after another, with
InProcessExecution.RunAsync. output.ExecutorIdnames the executor the output came from, documented as The unique identifier of the executor that yielded this output. The,-16pads it to 16 characters, so the texts line up.
Step 5: Run It
dotnet run
ShipOrder Pens: 7.50, shipped.
ManagerApproval Laptop: 1250.00 needs a manager's approval.
RejectOrder Free sample: rejected, the total is 0.

Each order took exactly one path. The pens came to 7.50, matched neither case and went to the default, ShipOrder. The laptop's 1250.00 matched the second case and went to ManagerApproval. The free sample's total of 0 matched the first case and went to RejectOrder.
The Complete File
using Microsoft.Agents.AI.Workflows;
// The steps, as plain C# functions turned into executors.
Func<Order, PricedOrder> price = order => new PricedOrder(order.Item, order.Quantity * order.UnitPrice);
Func<PricedOrder, string> reject = order => $"{order.Item}: rejected, the total is 0.";
Func<PricedOrder, string> approve = order => $"{order.Item}: {order.Total:0.00} needs a manager's approval.";
Func<PricedOrder, string> ship = order => $"{order.Item}: {order.Total:0.00}, shipped.";
ExecutorBinding priceOrder = price.BindAsExecutor("PriceOrder");
ExecutorBinding rejectOrder = reject.BindAsExecutor("RejectOrder");
ExecutorBinding managerApproval = approve.BindAsExecutor("ManagerApproval");
ExecutorBinding shipOrder = ship.BindAsExecutor("ShipOrder");
Workflow workflow = new WorkflowBuilder(priceOrder)
// One path per order: the first case that matches wins, and the default takes the rest.
.AddSwitch(priceOrder, paths => paths
.AddCase<PricedOrder>(order => order?.Total == 0, rejectOrder)
.AddCase<PricedOrder>(order => order?.Total >= 1000, managerApproval)
.WithDefault(shipOrder))
.WithOutputFrom(rejectOrder, managerApproval, shipOrder)
.Build();
Order[] orders =
[
new("Pens", 3, 2.50m),
new("Laptop", 1, 1250m),
new("Free sample", 0, 9.99m),
];
foreach (Order order in orders)
{
await using Run run = await InProcessExecution.RunAsync(workflow, order);
foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
if (workflowEvent is WorkflowOutputEvent output)
{
Console.WriteLine($"{output.ExecutorId,-16}{output.Data}");
}
}
}
record Order(string Item, int Quantity, decimal UnitPrice);
record PricedOrder(string Item, decimal Total);

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Putting a broad case before a narrow one | The broad case takes the messages first: cases are evaluated in the order they're added, and the first match wins | Put the most specific test first |
Leaving out WithDefault | A message that no case matches has nowhere to go. Microsoft's guide says WithDefault() ensures messages never get stuck | Add a default path, even one that only reports the message |
FAQ
Should I use a switch or conditional edges?
Both route messages. A conditional edge is an AddEdge with a condition, which suits a two-way choice. For more paths, Microsoft's Edges guide recommends the switch: Switch-case edges provide a cleaner, more maintainable solution when you need to route to multiple destinations based on different conditions.
Can one case send a message to more than one executor?
Yes. AddCase takes one or more executors after the test, and every executor in a matching case gets the message.
Can the steps be classes instead of functions?
Yes. A class-based executor works in a switch the same way, as the source or as a case's target. Its project needs the Microsoft.Agents.AI.Workflows.Generators package as well.
Conclusion
AddSwitch routes each message from one executor to exactly one path: the first AddCase whose test is true, or WithDefault when no test is. Write the tests in order from the most specific to the broadest, always add a default, and list every path's last executor in WithOutputFrom when its result is an output.
Additional Resources
- Edges — direct, conditional and switch-case edges, with Microsoft's switch-case example.
- Executors — function-based and class-based executors.
