Thursday, 26 November 2026

How to Call a Microsoft AI Agent from Python and .NET

Calling a Microsoft AI agent from code takes about ten lines in either Python or .NET once your Microsoft Foundry project is ready. This guide shows two ways to do it with complete, runnable code, and explains each line so you can adapt it to your own projects.

What does "calling a Microsoft AI agent" mean?

An AI agent is an LLM with instructions that can also call tools (your functions, web search, MCP servers) and keep conversation history. Microsoft gives you two parts that work together:

  • Microsoft Foundry (formerly Azure AI Foundry) hosts your models and, optionally, saved agents.
  • Microsoft Agent Framework is the open-source SDK for Python and .NET that builds and runs agents. It reached version 1.0 for both languages in April 2026, per the Agent Framework announcement.

This post covers both common ways to call an agent:

 Approach 1: Agent FrameworkApproach 2: Saved Foundry agent
Where the agent is definedIn your code, per run (an "ephemeral" agent)Saved and versioned in your Foundry project
How you call itagent.run(...) / agent.RunAsync(...)Responses API with a conversation
Python packageagent-framework-foundryazure-ai-projects 2.x
.NET packageMicrosoft.Agents.AI.FoundryAzure.AI.Projects + Azure.AI.Projects.Agents
Best forCustom tools, workflows, full control in codeAgents managed in the portal and shared by many apps

A note on older SDKs. The previous Azure AI Agent Service ("classic") agents are deprecated and scheduled to retire on March 31, 2027 (see the classic quickstart notice). Use the packages in this guide, not Azure.AI.Agents.Persistent or azure-ai-projects 1.x, for new work.

Prerequisites and setup

You need these before running any code below (from the Foundry Responses API quickstart):

  • An Azure subscription and a Microsoft Foundry project with a deployed model.
  • The Azure CLI, signed in with az login.
  • Python 3.10 or later, or the .NET 8 SDK or later.
  • Permission to create and use agents in the project. Older classic documentation names the Azure AI User role at project scope; confirm the current role for your tenant in the Foundry portal's access settings.

Find your project endpoint in the Foundry portal; it looks like this:

https://<resource-name>.services.ai.azure.com/api/projects/<project-name>

Set the environment variables. The samples below read them, so no endpoint or secret is ever hard-coded:

# Linux / macOS
export FOUNDRY_PROJECT_ENDPOINT="https://<resource-name>.services.ai.azure.com/api/projects/<project-name>"
export FOUNDRY_MODEL="<your deployed model name>"
# Windows PowerShell
$env:FOUNDRY_PROJECT_ENDPOINT = "https://<resource-name>.services.ai.azure.com/api/projects/<project-name>"
$env:FOUNDRY_MODEL = "<your deployed model name>"

FOUNDRY_MODEL is the deployment name you chose in Foundry, not necessarily the base model name.

Install packages.

# Python (Approach 1)
pip install agent-framework-foundry aiohttp azure-identity

# Python (Approach 2)
pip install "azure-ai-projects>=2.3.0" azure-identity
# .NET (Approach 1)
dotnet new console -n AgentDemo
cd AgentDemo
dotnet add package Microsoft.Agents.AI.Foundry --prerelease
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.Identity

# .NET (Approach 2)
dotnet add package Azure.AI.Projects
dotnet add package Azure.AI.Projects.Agents
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.Identity

Two things that trip people up: the Agent Framework Foundry package for .NET is still prerelease (hence --prerelease), and azure-ai-projects 2.x is not compatible with 1.x, so do not mix examples from older tutorials.

Approach 1 in Python: Microsoft Agent Framework

Here the agent is defined in your code and runs in your process. Each call goes to your Foundry project for model inference and tool orchestration. Create a file named hello_agent.py:

import asyncio
import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential


async def main() -> None:
    agent = Agent(
        client=FoundryChatClient(
            project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
            model=os.environ["FOUNDRY_MODEL"],
            credential=AzureCliCredential(),
        ),
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("What is the capital of France?")
    print(f"Agent: {result}")


if __name__ == "__main__":
    asyncio.run(main())

Run it after az login:

python hello_agent.py

How it works, line by line

  1. FoundryChatClient connects to your Foundry project using the endpoint and the model deployment name from the environment.
  2. AzureCliCredential uses your az login session, so there is no API key in the code.
  3. Agent(...) combines that client with instructions, the system prompt that shapes every answer.
  4. agent.run(...) is asynchronous, so it is awaited inside asyncio.run. The result prints as the agent's text answer.

Agent Framework does not read .env files by itself. If you keep settings in a .env file, install python-dotenv and call load_dotenv() at the top of your script, as the Agent Framework quickstart notes.

Approach 1 in .NET: Microsoft Agent Framework

Create the console project and packages from the setup section, then replace Program.cs with this code:

using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;

string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
    ?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");

AIAgent agent =
    new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a helpful assistant.",
        name: "Assistant");

Console.WriteLine($"Agent: {await agent.RunAsync("What is the capital of France?")}");

Run it after az login:

dotnet run

How it works, line by line

  1. The two environment variables are read once, and the app fails fast with a clear message if either is missing.
  2. AIProjectClient connects to your Foundry project. DefaultAzureCredential finds your Azure CLI login on a developer machine, or a managed identity when deployed.
  3. AsAIAgent(...) is an extension method from Microsoft.Agents.AI.Foundry. It turns the project client into an AIAgent with your model, instructions and name.
  4. RunAsync(...) sends the question and returns the agent's answer; string interpolation prints its text.

The same code works in a worker service, a console tool or an ASP.NET Core app, because AIAgent is a normal object you can register in dependency injection.

Approach 2 in Python: call a saved Foundry agent

With this approach the agent lives in your Foundry project with a name and versions, and your app only calls it. You can create it in the Foundry portal, or from code as below. The calls follow the Foundry get-started quickstart, with the endpoint, agent name and model moved into environment variables.

Step 1: create the agent once (create_agent.py). Running it again creates a new version of the same agent.

import os

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
from azure.identity import DefaultAzureCredential

project = AIProjectClient(
    endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)

agent = project.agents.create_version(
    agent_name=os.environ["FOUNDRY_AGENT_NAME"],
    definition=PromptAgentDefinition(
        model=os.environ["FOUNDRY_MODEL"],
        instructions="You are a helpful assistant that answers general questions",
    ),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")

Step 2: chat with it (chat_with_agent.py). The Foundry quickstart creates the agent and chats in one file; this version assumes the agent already exists (created above or in the portal), so it skips creation.

import os

from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

project = AIProjectClient(
    endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)

# An OpenAI client already bound to your agent
openai = project.get_openai_client(agent_name=os.environ["FOUNDRY_AGENT_NAME"])

# A conversation stores the history for multi-turn chat
conversation = openai.conversations.create()

response = openai.responses.create(
    conversation=conversation.id,
    input="What is the size of France in square miles?",
)
print(response.output_text)

# Follow-up: the agent remembers the previous turn
response = openai.responses.create(
    conversation=conversation.id,
    input="And what is the capital city?",
)
print(response.output_text)

Add the new variable to your environment first: FOUNDRY_AGENT_NAME=MyAgent. Then run python create_agent.py once and python chat_with_agent.py whenever you want to talk to it.

What to notice

  • get_openai_client(agent_name=...) returns a client that is already bound to your agent, so responses.create needs no agent argument.
  • conversations.create() gives you a conversation ID. Reusing it is what makes the follow-up question work. Store this ID in your database per user to continue chats later.
  • DefaultAzureCredential works on your laptop through az login, and in Azure through a managed identity.

Approach 2 in .NET: call a saved Foundry agent

These examples follow the C# tab of the Foundry get-started quickstart (packages Azure.AI.Projects, Azure.AI.Projects.Agents, Azure.AI.Extensions.OpenAI), with values moved into environment variables. Set FOUNDRY_AGENT_NAME (for example MyAgent) next to the earlier two variables.

Step 1: create the agent once. Run this as its own small console project, or keep it in a setup tool.

using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;

string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string agentName = Environment.GetEnvironmentVariable("FOUNDRY_AGENT_NAME")
    ?? throw new InvalidOperationException("FOUNDRY_AGENT_NAME is not set.");
string model = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
    ?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");

AIProjectClient projectClient = new(
    endpoint: new Uri(endpoint),
    tokenProvider: new DefaultAzureCredential());

ProjectsAgentDefinition agentDefinition = new DeclarativeAgentDefinition(model)
{
    Instructions = "You are a helpful assistant that answers general questions",
};

ProjectsAgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName,
    options: new(agentDefinition));
Console.WriteLine($"Agent created (id: {agent.Id}, name: {agent.Name}, version: {agent.Version})");

Step 2: chat with it. As in Python, the quickstart creates and chats in one file. This version assumes the agent already exists and skips creation.

using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.Identity;
using OpenAI.Responses;

#pragma warning disable OPENAI001

string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string agentName = Environment.GetEnvironmentVariable("FOUNDRY_AGENT_NAME")
    ?? throw new InvalidOperationException("FOUNDRY_AGENT_NAME is not set.");

AIProjectClient projectClient = new(
    endpoint: new Uri(endpoint),
    tokenProvider: new DefaultAzureCredential());

// A conversation stores the history for multi-turn chat
ProjectConversation conversation = projectClient.ProjectOpenAIClient
    .GetProjectConversationsClient()
    .CreateProjectConversation();

ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient
    .GetProjectResponsesClientForAgent(
        defaultAgent: agentName,
        defaultConversationId: conversation.Id);

ResponseResult response = responsesClient.CreateResponse("What is the size of France in square miles?");
Console.WriteLine(response.GetOutputText());

// Follow-up: the agent remembers the previous turn
response = responsesClient.CreateResponse("And what is the capital city?");
Console.WriteLine(response.GetOutputText());

What to notice

  • GetProjectResponsesClientForAgent(defaultAgent, defaultConversationId) binds the client to your saved agent and your conversation, so every CreateResponse call continues the same chat.
  • #pragma warning disable OPENAI001 silences the experimental-API warning the quickstart also uses.
  • Keep conversation.Id per user if you want to resume the conversation in a later request.

Level up: streaming, memory and tools

The examples below extend Approach 1. Each snippet reuses the agent object created in the earlier sections.

Stream the answer as it is generated

Streaming shows text token by token, which feels much faster in chat UIs.

# Python
print("Agent: ", end="", flush=True)
async for chunk in agent.run("Tell me a fun fact.", stream=True):
    if chunk.text:
        print(chunk.text, end="", flush=True)
print()
// .NET
Console.Write("Agent: ");
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a fun fact."))
{
    Console.Write(update);
}
Console.WriteLine();

Remember the conversation with a session

By default each call is independent. Create a session and pass it to every call to keep history (see the session guide).

# Python
session = agent.create_session()
first = await agent.run("My name is Alice and I love hiking.", session=session)
second = await agent.run("What do you remember about me?", session=session)
print(second)
// .NET
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("My name is Alice and I love hiking.", session));
Console.WriteLine(await agent.RunAsync("What do you remember about me?", session));

Sessions can be serialized and restored later (session.to_dict() and AgentSession.from_dict(...) in Python, SerializeSession and DeserializeSessionAsync in .NET), which lets you store a user's chat in your database.

Give the agent your own function as a tool

Tools are how an agent does real work: query a database, call your API, send an email. The agent decides when to call the function and writes the answer from its result. This sample uses a fake weather function, taken from the Foundry quickstart.

# Python: weather_agent.py
import asyncio
import os
from random import randint
from typing import Annotated

from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
from pydantic import Field


@tool(approval_mode="never_require")
def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    conditions = ["sunny", "cloudy", "rainy", "stormy"]
    return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."


async def main() -> None:
    agent = Agent(
        client=FoundryChatClient(
            project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
            model=os.environ["FOUNDRY_MODEL"],
            credential=AzureCliCredential(),
        ),
        instructions="You are a helpful weather agent.",
        tools=get_weather,
    )

    result = await agent.run("What's the weather like in Seattle?")
    print(f"Agent: {result}")


if __name__ == "__main__":
    asyncio.run(main())
// .NET: Program.cs
using System.ComponentModel;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

[Description("Get the weather for a given location.")]
static string GetWeather(
    [Description("The location to get the weather for.")] string location)
{
    string[] conditions = ["sunny", "cloudy", "rainy", "stormy"];
    Random rng = Random.Shared;
    return $"The weather in {location} is {conditions[rng.Next(conditions.Length)]} with a high of {rng.Next(10, 31)}°C.";
}

AITool weatherTool = AIFunctionFactory.Create(GetWeather);

string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
    ?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");

AIAgent agent =
    new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a helpful weather agent.",
        name: "WeatherAssistant",
        tools: [weatherTool]);

Console.WriteLine($"Agent: {await agent.RunAsync("What's the weather like in Seattle?")}");

The description text on the function and its parameters is what the model reads to decide when and how to call it, so write it clearly. The Python approval_mode="never_require" setting means the tool runs without asking a human first; for tools that change data, keep human approval on.

Agent Framework also supports built-in tools such as web search (FoundryChatClient.get_web_search_tool() in Python, new HostedWebSearchTool() in .NET), which you can combine with your own functions in the same tools list.

Production tips: security and a web API wrapper

Security and reliability checklist

  • No secrets in code. The samples use token credentials, so there is no API key. Keep endpoints in environment variables, app settings or Key Vault.
  • Use a specific credential in production. Microsoft warns that DefaultAzureCredential is convenient for development but can add latency and probe unintended credential sources in production. Prefer ManagedIdentityCredential, and give that managed identity access to your Foundry project.
  • Create the agent once. Build the Agent or AIAgent at startup and reuse it, not on every request.
  • Validate input. Limit message length, reject empty messages and never let user text decide which tools run without checks.
  • Keep human approval on risky tools that change data or spend money.
  • Handle failures. Catch exceptions around the agent call, log the details on the server, and return a generic message to the client.
  • Add tracing. Connecting Application Insights to your project does not trace your app automatically; configure Agent Framework observability in the app.

Expose the agent as a web API in Python (FastAPI):

import logging
import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential, ManagedIdentityCredential
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

logger = logging.getLogger("agent-api")


def build_credential():
    # Managed identity in Azure, Azure CLI login on a developer machine
    if os.environ.get("APP_ENV") == "production":
        return ManagedIdentityCredential()
    return AzureCliCredential()


agent = Agent(
    client=FoundryChatClient(
        project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
        model=os.environ["FOUNDRY_MODEL"],
        credential=build_credential(),
    ),
    instructions="You are a helpful assistant.",
)

app = FastAPI()


class ChatRequest(BaseModel):
    message: str = Field(min_length=1, max_length=2000)


class ChatResponse(BaseModel):
    answer: str


@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest) -> ChatResponse:
    try:
        result = await agent.run(request.message)
    except Exception as exc:
        logger.exception("Agent call failed")
        raise HTTPException(status_code=502, detail="The AI agent is unavailable.") from exc
    return ChatResponse(answer=str(result))

Install fastapi and uvicorn, then run uvicorn main:app --reload.

Expose the agent as a web API in .NET (ASP.NET Core Minimal API). Create the project with dotnet new web and add the same three packages as Approach 1:

using Azure.AI.Projects;
using Azure.Core;
using Azure.Identity;
using Microsoft.Agents.AI;

var builder = WebApplication.CreateBuilder(args);

string endpoint = builder.Configuration["FOUNDRY_PROJECT_ENDPOINT"]
    ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string model = builder.Configuration["FOUNDRY_MODEL"]
    ?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");

// Managed identity in Azure, Azure CLI login on a developer machine
TokenCredential credential = builder.Environment.IsProduction()
    ? new ManagedIdentityCredential()
    : new AzureCliCredential();

builder.Services.AddSingleton<AIAgent>(_ =>
    new AIProjectClient(new Uri(endpoint), credential)
        .AsAIAgent(
            model: model,
            instructions: "You are a helpful assistant.",
            name: "Assistant"));

var app = builder.Build();

app.MapPost("/chat", async (ChatRequest request, AIAgent agent, ILogger<Program> logger) =>
{
    if (string.IsNullOrWhiteSpace(request.Message) || request.Message.Length > 2000)
    {
        return Results.BadRequest(new { error = "Message is required and must be at most 2000 characters." });
    }

    try
    {
        var result = await agent.RunAsync(request.Message);
        return Results.Ok(new ChatResponse(result.ToString()));
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "Agent call failed");
        return Results.Problem("The AI agent is unavailable.", statusCode: StatusCodes.Status502BadGateway);
    }
});

app.Run();

public record ChatRequest(string Message);
public record ChatResponse(string Answer);

The Agent Framework team also documents exposing a Foundry-connected agent through ASP.NET Core and AG-UI endpoints (public preview) in its Agent Framework blog if you need a chat UI protocol.

Troubleshooting common errors

These are the usual causes; check them in this order.

SymptomLikely causeFix
401 or 403 from the projectNot signed in, or your user or managed identity lacks access to the projectRun az login, then confirm the role assignment on the Foundry project
404, "model not found" or "agent not found"Wrong endpoint, deployment name or agent nameCompare FOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODEL and FOUNDRY_AGENT_NAME with the portal; the model value is the deployment name
"Environment variable is not set"The variable was set in another terminal, or Python did not load your .env fileRestart the terminal or IDE; in Python call load_dotenv()
NuGet cannot find Microsoft.Agents.AI.FoundryThe package is prereleaseAdd --prerelease to dotnet add package
Import errors or missing classes such as PromptAgentDefinitionMixed azure-ai-projects 1.x and 2.x codeUse a clean virtual environment with azure-ai-projects>=2.3.0
Compiler warning OPENAI001The OpenAI Responses types are marked experimentalAdd #pragma warning disable OPENAI001, as the quickstart does
Slow first call in productionDefaultAzureCredential tries several credential sourcesUse ManagedIdentityCredential in Azure
Empty answer textThe model returned only tool calls or a blocked responseCheck the response object and your agent instructions; the quickstart raises an error when the text is empty

Summary

  • For custom logic and tools in your code, use Microsoft Agent Framework: Agent and FoundryChatClient in Python, AIProjectClient.AsAIAgent(...) in .NET.
  • For agents managed in Foundry and shared across apps, create a versioned prompt agent and call it through a conversation: get_openai_client(agent_name=...) in Python, GetProjectResponsesClientForAgent(...) in .NET.
  • Use environment variables and token credentials, keep one agent instance per app, and use a managed identity in production.

Microsoft is releasing Agent Framework and Foundry SDK updates frequently, and some packages here are prerelease, so pin package versions and re-check the docs before upgrading.

Sources

Wednesday, 25 November 2026

.NET 11 Is Here: Complete Guide with Code Examples

 .NET 11 at a glance

.NET 11 was released on November 10, 2026 as a Standard Term Support (STS) release with two years of support, and it brings C# 15 with union types, a faster SDK, a much larger library surface, and deeper AI tooling. Per the official announcement, STS and LTS share the same quality and servicing policies; only the support length differs.

Item

Detail

Release date

November 10, 2026 (.NET Conf 2026 runs November 10-13)

Support model

STS, 2 years

Default language

C# 15 for net11.0 projects

.NET 10

Remains the supported LTS option

.NET 8 and .NET 9

End of support on November 10, 2026

Ecosystem

7,000+ contributors, 589,000+ unique NuGet packages, 1.1 trillion+ package downloads

Install via

.NET 11 SDK, Visual Studio 2026, or Visual Studio Code with C# Dev Kit

If you tested a release candidate, move to the final SDK, runtime and matching package and workload versions.

Getting started and upgrading

Create and run a .NET 11 console app in two commands:

dotnet new console -n HelloDotnet11 -f net11.0
dotnet run --project HelloDotnet11

Installing the SDK alone does not retarget your apps. To upgrade an existing solution:

  1. Update global.json if you pin an SDK, and install the matching SDK on developer machines and build agents.
  2. Retarget projects to net11.0 (keep any platform suffix) and update packages and workloads.
  3. Review the .NET 11 breaking changes and the updated minimum CPU requirements.
  4. Run your tests and measure under realistic workloads. Validate publishing mode, container images, native dependencies and hosts.

A minimal project file after retargeting:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
  </PropertyGroup>
</Project>

C# 15: the language headliners

C# 15 is the default for any project targeting net11.0 with the .NET 11 SDK. Only the memory safety preview needs <LangVersion>preview</LangVersion>. Examples below follow the C# 15 what's new page.

1. Union types

A union declares a value that is exactly one of a fixed set of case types. Each case converts implicitly to the union, and switch expressions are checked for exhaustiveness, so you no longer need a catch-all arm or a hand-rolled OneOf type.

public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);

public union Pet(Cat, Dog, Bird);

Pet pet = new Dog("Rex");

string name = pet switch
{
    Dog d => d.Name,
    Cat c => c.Name,
    Bird b => b.Name,
};

A realistic use is a lookup result that is either a hit or a miss, as shown in the announcement:

ProductLookup result = new Product(42, "Mechanical keyboard");

string message = result switch
{
    Product product => $"Found {product.Name}",
    ProductNotFound missing => $"No product with ID {missing.Id}",
};

public sealed record Product(int Id, string Name);
public sealed record ProductNotFound(int Id);
public union ProductLookup(Product, ProductNotFound);

If you later add a case to the union, every switch that does not handle it produces a compiler warning. That is the main benefit over returning object or a base class.

2. Closed hierarchies

Mark a class closed and only types in the same assembly can derive from it. The compiler then knows every direct descendant and can check pattern matching over the hierarchy.

public closed record class GateState;
public record class Closed : GateState;
public record class Open(float Percent) : GateState;

string Describe(GateState state) => state switch
{
    Closed => "closed",
    Open(var percent) => $"{percent}% open",
    // No warning: every direct descendant is handled.
};

Things to remember:

  • A closed class is implicitly abstract, and cannot also be sealed, static or explicitly abstract.
  • Closing is not transitive. A non-closed descendant can still be derived from in other assemblies. Mark intermediate types closed too if you want exhaustiveness further down.

Use union when the cases are unrelated types, and closed when they already share a base class.

3. Collection expression arguments

Put a with(...) element first in a collection expression to pass arguments to the constructor or factory of the target collection.

string[] values = ["one", "two", "three"];

// Capacity argument to the List<T> constructor
List<string> names = [with(capacity: values.Length * 2), .. values];

// Comparer argument to the HashSet<T> constructor
HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"];
Console.WriteLine(set.Count); // 1

This removes the old choice between a concise collection expression and a constructor call when you need a comparer or capacity.

4. Extension indexers

Indexers can now live in an extension block. Because an indexer is an instance member, the block needs a named receiver parameter.

public static class SequenceIndexer
{
    extension(IEnumerable<int> sequence)
    {
        public int this[int index] => sequence.ElementAt(index);
    }
}

IEnumerable<int> numbers = Enumerable.Range(1, 10);
int third = numbers[2]; // 3

5. Labeled break and continue

break and continue can name a label on an enclosing loop or switch, which replaces Boolean flags and goto in nested loops. Put the label directly on the statement it identifies.

outer: for (int row = 0; row < grid.Height; row++)
{
    for (int column = 0; column < grid.Width; column++)
    {
        if (grid[row, column].IsBlocked)
        {
            continue outer;
        }

        if (grid[row, column].IsGoal)
        {
            break outer;
        }
    }
}

The IDE0410 style rule flags flag-and-goto patterns that a labeled jump can replace.

6. Static interface members on older runtimes

Interfaces can declare non-virtual static members even when the runtime lacks default interface implementation support. Instance default implementations, static abstract and static virtual members, and protected members still need runtime support.

public interface IMeasurement
{
    public static double ToMeters(double centimeters) => centimeters / 100;
}

double meters = IMeasurement.ToMeters(250);

7. Memory safety (preview, opt-in)

This is the start of a multi-release effort to tie the unsafe context to operations that touch unmanaged memory rather than to pointer types. It needs <LangVersion>preview</LangVersion>, and the updated-memory-safety-rules compiler feature flag for the new caller obligations. With the preview, you can declare pointer types, use &, use fixed, convert stackalloc to a pointer and apply sizeof to unmanaged types without an unsafe block. Dereferencing (*p), member access (p->member), element access and function pointer calls still require unsafe.

int number = 42;
int* pointer = &number;

int[] numbers = [10, 20, 30];
fixed (int* first = numbers)
{
    // Dereferencing still requires an unsafe context.
}

The preview also adds unsafe(expression) for a single expression where an unsafe block cannot appear (for example, a field initializer) and a safe keyword for extern members and layout-type fields.

Runtime and performance

The runtime team shipped hundreds of optimizations; Stephen Toub's "Performance Improvements in .NET 11" post covers them in depth. The headline items from the announcement:

  • JIT: fewer redundant bounds checks and branches, better devirtualization, more constant folding, and more optimized SequenceEqual calls.
  • Native AOT: interface dispatch uses a shared helper, which reduces code at each call site.
  • Hardware: FP16 instruction support for Half on supported x64 and Arm64 hardware, plus new vector construction and composition APIs.
  • Diagnostics: in-process crash report logging (managed stack, module info, runtime state) now works on Linux and macOS, not just on mobile.

Runtime Async (preview)

Runtime Async moves async suspension and resumption into the runtime itself. Profilers and debuggers can then show your async methods directly in live call stacks instead of compiler-generated state machines. Opt in per project for net11.0; you do not need EnablePreviewFeatures.

<PropertyGroup>
  <Features>runtime-async=on</Features>
</PropertyGroup>

Because it is a preview, test your dependencies and diagnostics tooling before adopting it in production.

New library APIs

Examples in this section come from the .NET 11 libraries what's new page.

Process API: run and capture in one call

Process.Run, Process.RunAsync, Process.RunAndCaptureText and Process.RunAndCaptureTextAsync remove the manual OutputDataReceived and ErrorDataReceived wiring. There are also ReadAllText, ReadAllBytes, ReadAllLines (which tells stdout from stderr via ProcessOutputLine) and async variants.

// One-shot capture: stdout and stderr together, plus exit code.
ProcessTextOutput result = await Process.RunAndCaptureTextAsync(
    "git", ["status", "--porcelain"]);

Console.WriteLine(result.StandardOutput);
Console.WriteLine($"Exit code: {result.ExitStatus.ExitCode}");

Advanced controls arrive too: Process.StartAndForget, ProcessStartInfo.StartDetached, ProcessStartInfo.StartSuspended, ProcessStartInfo.KillOnParentExit (Windows only), Process.Signal(PosixSignal) and Process.WaitForExitStatusAsync, whose ProcessExitStatus distinguishes a normal exit from signal-based termination.

Zstandard compression

ZstandardStream and ZstandardEncoder join DeflateStream, GZipStream and BrotliStream in System.IO.Compression. The announcement also lists span-based APIs and CRC32 validation for ZIP reads. The docs page does not include a Zstandard code sample, so check the API reference before relying on specific member names.

In-memory stream adapters

Four new Stream types wrap in-memory data without copying: ReadOnlyMemoryStream, WritableMemoryStream (fixed size), ReadOnlySequenceStream and StringStream.

using System.IO;
using System.Text;

// Pass a string to an API that takes a Stream, with no intermediate byte[] needed.
using Stream config = new StringStream(yamlText, Encoding.UTF8);
var settings = ParseConfiguration(config);

// Expose an existing buffer as a read-only stream, for example as an HTTP request body.
ReadOnlyMemory<byte> payload = GetPayload();
using Stream body = new ReadOnlyMemoryStream(payload);
await httpClient.PostAsync(uri, new StreamContent(body));

System.Text.Json: unions and JSON Lines

C# unions serialize as the plain value of the active case, with no wrapper or $type discriminator.

public union Reading(int, string);

Reading reading = new("hello");
string json = JsonSerializer.Serialize(reading);
Reading copy = JsonSerializer.Deserialize<Reading>(json);
Console.WriteLine(json);       // "hello"
Console.WriteLine(copy.Value); // hello

When cases are objects, pick the right one from the property names with a structural classifier. A payload that matches zero or several cases throws JsonException.

[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union PetUnion(Dog, Cat);

public sealed record Dog(string Name, string Breed);
public sealed record Cat(string Name, int Lives);

PetUnion? pet = JsonSerializer.Deserialize<PetUnion>(
    """{"Name":"Misty","Lives":9}""",
    PetJsonContext.Default.PetUnion);

Console.WriteLine(pet?.Value is Cat); // True

F# discriminated unions are supported too, but through reflection only: no source generation, trimming or Native AOT.

JsonSerializer.SerializeAsyncEnumerable now writes JSON Lines when you pass topLevelValues: true (LF line endings). The default writes a JSON array.

static async IAsyncEnumerable<int> GenerateNumbers()
{
    for (int i = 0; i < 5; i++)
    {
        yield return i;
        await Task.Yield();
    }
}

using var jsonlStream = new MemoryStream();
PipeWriter jsonlPipe = PipeWriter.Create(jsonlStream);

// Writes one value per line: 0\n1\n2\n3\n4\n
await JsonSerializer.SerializeAsyncEnumerable(
    jsonlPipe,
    GenerateNumbers(),
    topLevelValues: true);
await jsonlPipe.CompleteAsync();

LINQ: LeftJoin, RightJoin and FullJoin

These operators return tuples directly and exist on Enumerable, Queryable and AsyncEnumerable. Missing sides are default.

var products = new List<(int Id, string Name, string? Category)>
{
    (1, "Laptop", "Electronics"),
    (2, "Mouse", "Electronics"),
    (3, "Orphan", null), // No matching category
};
var categories = new List<(string Name, string Description)>
{
    ("Electronics", "Electronic devices"),
    ("Furniture", "Office furniture"), // No matching product
};

var fullJoined = products.FullJoin(
    categories,
    p => p.Category,
    c => c.Name);

foreach (var (product, category) in fullJoined)
    Console.WriteLine(
        $"{product.Name ?? "(none)"}: {category.Description ?? "(none)"}");
// Laptop: Electronic devices
// Mouse: Electronic devices
// Orphan: (none)
// (none): Office furniture

Other additions listed in the announcement include expanded numeric types, DNS resolution, cryptography and tracing configuration. Experimental APIs are marked in the library overview.

ASP.NET Core 11 and Blazor

Examples follow the ASP.NET Core 11 release notes.

Union types in Minimal APIs

Unions work anywhere System.Text.Json is used, including request and response bodies. OpenAPI describes them with anyOf.

public union UnionIntString(int, string);

app.MapGet("/value", () => new UnionIntString(42));

Limits: unions cover JSON bodies only, not route, query, header or form binding. SignalR unions need the JSON hub protocol (not MessagePack or Newtonsoft.Json). When several cases share one JSON shape, add a [JsonUnion] classifier.

Async validation

Validators can now await I/O, such as a database check, end to end in Minimal APIs and Blazor forms. Derive from AsyncValidationAttribute for a property rule, or implement IAsyncValidatableObject for whole-object rules.

using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;

public sealed class UniqueEmailAttribute : AsyncValidationAttribute
{
    // This attribute validates asynchronously only.
    protected override ValidationResult? IsValid(object? value, ValidationContext context) =>
        throw new InvalidOperationException("Validate this attribute with IsValidAsync.");

    protected override async Task<ValidationResult?> IsValidAsync(
        object? value, ValidationContext context, CancellationToken cancellationToken)
    {
        var users = context.GetRequiredService<IUserService>();

        if (value is string email && await users.EmailExistsAsync(email, cancellationToken))
        {
            return new ValidationResult("That email is already registered.");
        }

        return ValidationResult.Success;
    }
}

Register validation once and the framework validates the request before your endpoint runs:

builder.Services.AddValidation();

app.MapPost("/reservations", (ReservationRequest request) =>
    Results.Ok(request));

IAsyncValidatableObject.ValidateAsync returns IAsyncEnumerable<ValidationResult>. It extends IValidatableObject, so you implement the synchronous Validate method as well.

OpenAPI 3.2 by default

Microsoft.AspNetCore.OpenApi now uses Microsoft.OpenApi 3.3.1 and generates OpenAPI 3.2 documents by default. This is a breaking change for tooling that expects an older version, so pin the version if needed.

builder.Services.AddOpenApi(options =>
{
    // Back to 3.1 if your consumers are not ready for 3.2.
    options.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_1;
});

OpenAPI 3.2 also describes HTTP QUERY operations, and SseItem<T> server-sent event streams with itemSchema for text/event-stream (return them with TypedResults.ServerSentEvents(...)). The OpenApiGenerationEnvironment MSBuild property sets the environment used for build-time generation.

SignalR: refresh authentication without reconnecting

Connections can renew credentials when the access token expires instead of dropping.

// Server
app.MapHub<ChatHub>("/chat", options =>
{
    options.EnableAuthenticationRefresh = true;
    options.CloseOnAuthenticationExpiration = true;

    // Optional: accept the refreshed identity only if it is the same subject.
    options.OnAuthenticationRefresh = context =>
    {
        var previousSubject = context.PreviousUser.FindFirstValue("sub")
            ?? context.PreviousUser.FindFirstValue(ClaimTypes.NameIdentifier);
        var newSubject = context.NewUser.FindFirstValue("sub")
            ?? context.NewUser.FindFirstValue(ClaimTypes.NameIdentifier);

        return Task.FromResult(
            previousSubject is not null &&
            string.Equals(previousSubject, newSubject, StringComparison.Ordinal));
    };
});

public class ChatHub : Hub
{
    public override Task OnAuthenticationRefreshedAsync()
    {
        // The connection's User has been updated with the refreshed token.
        return Task.CompletedTask;
    }
}
// .NET client
await using var connection = new HubConnectionBuilder()
    .WithUrl("https://example.com/chat")
    .WithAuthenticationRefresh(options =>
    {
        // EnableAutoRefresh is true by default.
        options.RefreshBeforeExpiration = TimeSpan.FromMinutes(1);
    })
    .Build();

connection.AuthenticationRefreshed += context => Task.CompletedTask;
connection.AuthenticationRefreshFailed += context => Task.CompletedTask;

await connection.StartAsync();

// Refresh immediately after acquiring a token with updated claims.
await connection.RefreshAuthenticationAsync();

The TypeScript client offers withAuthenticationRefresh and refreshAuthentication(). Clients can also cancel regular (non-streaming) hub invocations, which triggers the hub method's CancellationToken on the server.

Blazor improvements

CacheView caches the rendered output of a subtree during static SSR. On a hit, markup is replayed without creating child components.

<CacheView VaryByQuery="category" ExpiresAfter="TimeSpan.FromMinutes(5)">
    <ProductList Category="@Category" />
</CacheView>

Automatic circuit pause is opt-in for Interactive Server apps. It pauses circuits of inactive tabs to free server memory (default delay 2 minutes) and needs the Microsoft.AspNetCore.Components.Server.AutoPause package.

app.MapRazorComponents<App>()
    .WithBrowserOptions(options => options.AddAutoPause(p => p.HiddenDelay = TimeSpan.FromSeconds(30)));

Virtualize and QuickGrid can open at an item and scroll to one on demand with InitialItemIndex and ScrollToItemAsync. Out-of-range indexes are clamped, and calling it before the first interactive render throws InvalidOperationException.

<Virtualize TItem="Product" Items="products" InitialItemIndex="500" @ref="list">
    <div class="product">@context.Name</div>
</Virtualize>

<button @onclick="GoToTop">Back to top</button>

@code {
    private Virtualize<Product> list = default!;
    private List<Product> products = ProductCatalog.All;

    private async Task GoToTop() => await list.ScrollToItemAsync(0);
}

Also new: client-side validation for static SSR forms, and authentication refresh that lets Interactive Server components react to claim changes.

Entity Framework Core 11

EF Core 11 requires the .NET 11 SDK and runtime; it does not run on earlier .NET versions or .NET Framework. Examples follow the EF Core 11 what's new page, which notes that EF 11 features are still in development.

FullJoin translation

The new LINQ FullJoin translates to a SQL FULL JOIN on relational providers.

var results = await context.Customers
    .FullJoin(
        context.Orders,
        c => c.Id,
        o => o.CustomerId,
        (c, o) => new { Customer = c, Order = o })
    .ToListAsync();
SELECT [c].[Id], [c].[Name], [o].[Id], [o].[CustomerId], [o].[OrderDate]
FROM [Customers] AS [c]
FULL JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId]

Complex types and JSON columns with TPT and TPC inheritance

These combinations were not possible before. Complex types now map on entities that use table-per-type or table-per-concrete-type inheritance.

public abstract class Animal
{
    public int Id { get; set; }
    public string Name { get; set; }
    public required AnimalDetails Details { get; set; }
}

public class Dog : Animal { public string Breed { get; set; } }
public class Cat : Animal { public bool IsIndoor { get; set; } }

[ComplexType]
public class AnimalDetails
{
    public DateTime BirthDate { get; set; }
    public string? Veterinarian { get; set; }
}
// Map Details to a JSON column on a TPT hierarchy
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Animal>()
        .UseTptMappingStrategy()
        .ComplexProperty(a => a.Details, b => b.ToJson());
}

Related model-building changes: you can chain lambdas such as Property(e => e.Details.Description).HasMaxLength(500), and define keys and indexes on complex type properties, for example HasIndex(c => c.Address.PostalCode) or HasIndex("Items[].Sku") for JSON-mapped complex collections.

Vector indexes and vector search (SQL Server, experimental)

VECTOR_SEARCH() and SQL Server vector indexes are experimental, and so are the EF APIs for them, so expect changes.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .HasVectorIndex(b => b.Embedding, "cosine");
}

var blogs = await context.Blogs
    .VectorSearch(b => b.Embedding, embedding, "cosine")
    .OrderBy(r => r.Distance)
    .Take(5)
    .WithApproximate()   // approximate nearest neighbor; omit for exact kNN
    .ToListAsync();

Behavior change: SqlVector<T> columns are no longer included in entity SELECT statements. They still work in WHERE and ORDER BY, and they load when you project them explicitly.

Migrations improvements

# Create and apply a migration in one step (compiled with Roslyn at runtime)
dotnet ef database update InitialCreate --add

# Run against every DbContext
dotnet ef migrations list --context "*"
  • dotnet ef migrations remove accepts --connection and --offline (not together), and dotnet ef database drop accepts --connection and --force.
  • dotnet ef reads defaults from .config/dotnet-ef.json; command-line options win.
  • -NoBuild is available for Add-Migration and Update-Database in Package Manager Console.
  • The model snapshot now records the latest migration ID, so divergent branches surface as a merge conflict.
  • Skip the database foreign key constraint but keep the relationship for queries and change tracking:
modelBuilder.Entity<Blog>()
    .HasMany(e => e.Posts)
    .WithOne(e => e.Blog)
    .HasForeignKey(e => e.BlogId)
    .ExcludeForeignKeyFromMigrations();

Other notable changes

  • Faster SQL: fewer unnecessary joins for reference navigations and split queries, and redundant keys dropped from ORDER BY. The docs cite 29% faster in one split-query scenario and 22% in one single-query scenario.
  • GroupBy: better translation, including aggregates over reference navigations using joins rather than correlated subqueries.
  • New operators: MaxByAsync and MinByAsync, for example await context.Blogs.MaxByAsync(b => b.Posts.Count()).
  • SQL Server: EF.Functions.JsonPathExists() (SQL Server 2022+), EF.Functions.JsonContains(), FreeTextTable() and ContainsTable() full-text functions, EF.Functions.DateTrunc(), and a new default compatibility level of 160 for UseSqlServer.
  • Cosmos DB: complex types, indexing policy, transactional batches, bulk execution and a System.Text.Json serializer. The serializer change is breaking: __jObject was removed and unmapped properties are no longer preserved on round-trip.
  • Analyzer: warns when ToAsyncEnumerable is used instead of AsAsyncEnumerable on EF queries.

SDK and developer tooling

Commands below come from the .NET 11 SDK what's new page unless noted.

  • Faster CLI: the Native AOT CLI host is on by default, so help and version commands skip managed startup, and the MSBuild server stays warm between invocations. Linux and macOS SDK installers are smaller thanks to assembly deduplication.
  • File-based apps across files: a single-file C# app can now pull in other files with #:include.
#:include helpers.cs
#:include models/customer.cs

Console.WriteLine(Helpers.FormatOutput(new Customer()));
  • Solution filters from the CLI: create and edit .slnf files without hand-editing JSON.
dotnet new slnf --parent-solution MySolution.slnx --name Tests
dotnet sln Tests.slnf add tests/Tests/Tests.csproj
dotnet sln Tests.slnf add src/Lib/Lib.csproj
dotnet sln Tests.slnf list
dotnet sln Tests.slnf remove src/Lib/Lib.csproj
  • dotnet test run-level limits (Microsoft.Testing.Platform). Put these before --.
# Stop the complete run after 90 seconds (exit code 3 on timeout).
dotnet test --timeout 90s

# Stop after five failed, errored, timed-out or cancelled results (exit code 13).
dotnet test --maximum-failed-tests 5
  • dotnet watch: Aspire app-host integration, relaunch after a crash on the next file change, and device selection for mobile projects (dotnet watch --device <device-id>). iOS Simulator projects need <MtouchLink>None</MtouchLink>.
  • Reproducible container images: set SOURCE_DATE_EPOCH and the same inputs produce the same image digest. Remote publishes also skip layers that already exist; set ContainerPushNoCache=true to bypass that.
dotnet publish /t:PublishContainer \
  -p:ContainerRegistry=registry.example.com \
  -p:SOURCE_DATE_EPOCH="$(git log -1 --pretty=%ct)"
  • NuGet minimum package age: ignore packages published in the last N hours when versions are picked automatically, a useful guard against freshly published malicious packages. It does not replace vulnerability checks. An explicit version bypasses the filter, and restore fails with NU1020 for floating references that violate it.
dotnet nuget add source https://api.nuget.org/v3/index.json --name public --min-publish-age-hours 24 --configfile nuget.config
dotnet nuget update source public --min-publish-age-hours 48 --configfile nuget.config
  • dotnetup (public preview): installs and updates SDKs and runtimes in the user account with side-by-side versions. The SDK page does not cover it, so see the announcement for current details.
  • AI-assisted tooling: .NET Skills gives coding agents task-specific guidance, .NET MAUI DevFlow (experimental) exposes a running app's visual tree and screenshots to agents, and the .NET Upgrade canvas visualizes a GitHub Copilot upgrade session.

AI building blocks in .NET 11

The announcement groups the AI story into templates, abstractions, agents and UI.

  • MCP server template: scaffold a Model Context Protocol server built on the official MCP C# SDK, with a sample tool included.
dotnet new mcpserver -o MyMcpServer
  • Microsoft.Extensions.AI (MEAI): provider-neutral abstractions such as IChatClient and IEmbeddingGenerator that compose with dependency injection, caching and OpenTelemetry. They ship as NuGet packages.
  • Microsoft Agent Framework (MAF): agents with tool calling and conversation state, plus workflows. Agents can connect to MCP tools and expose AG-UI endpoints (AG-UI hosting is prerelease).
  • Blazor AI components (experimental): Microsoft.AspNetCore.Components.AI offers streaming chat, tool rendering, approval flows and shared UI state, works with any IChatClient, and stays prerelease throughout .NET 11.
  • Data layer: EF Core 11 adds experimental SQL Server vector indexes and approximate vector search (see the EF Core section), and System.Text.Json now handles unions, which helps model tool results and agent messages.

The announcement describes these at overview level only, so for API-level samples follow the Microsoft Learn documentation for each package.

.NET MAUI, Windows desktop and F# 11

.NET MAUI

  • CoreCLR is now the default runtime on every platform. Where Apple platforms disallow JIT, precompiled code and the interpreter are used.
  • Native AOT is opt-in, with experimental Android support.
  • XAML Incremental Hot Reload (preview) updates live pages and controls, including supported structural edits, and is on by default in Debug builds.
  • Implicit XAML namespace declarations cut boilerplate. Windows uses the CollectionView2 handler by default, and Android Shell uses a handler-based architecture.
  • New mobile test templates and device selection for dotnet test.
  • Breaking: the optional Microsoft.Maui.Controls.Compatibility package no longer ships. MAUI follows its own support policy.

WinUI, Windows Forms and WPF

  • WinUI 3 (via the Windows App SDK) is recommended for new native Windows apps, and the SDK also exposes modern Windows APIs to WPF and WinForms.
  • Windows Forms: opt-in modern visual styles at application or control level, reaction to system visual and accessibility settings, deferred form reveal, and painting suspension during bulk updates.
  • WPF: reliability fixes for Fluent backdrops, window manager failures and weak-event cleanup. Self-contained publishing now includes a native dependency for mixed-mode assemblies.

F# 11

Lower compiler memory use, fewer allocations in FSharp.Core collection operations, ways to bound concurrent async work, and a preview of Runtime Async support for custom computation-expression builders.

Breaking changes, cautions and verdict

The announcement links to documentation rather than listing every breaking change, so read the full .NET 11 breaking changes list before upgrading. The items it names:

Area

What to know

EF Core 11

Requires .NET 11; it will not run on earlier versions

Hardware

Minimum CPU requirements were updated

OpenAPI

Generated documents default to 3.2; pin an earlier version if consumers need it

.NET MAUI

Microsoft.Maui.Controls.Compatibility no longer ships; Native AOT on Android is experimental

System.Text.Json

F# union support is reflection-based, with no source generation, trimming or Native AOT

Preview features

Runtime Async, memory safety rules, Blazor AI components and EF vector search can change

Cosmos DB provider

__jObject removed; unmapped properties are not preserved on round-trip

A reader comment on the announcement (not part of the article, and not verified here) reports a change in double-to-decimal conversion behavior and a MAUI CollectionView regression on Windows. Treat both as leads to check against Microsoft's compatibility documentation and your own tests.

Verdict. If you are on .NET 8 or .NET 9, plan the move now, since both lose support on November 10, 2026. For production apps that prefer a long support window, .NET 10 LTS remains an option, while .NET 11 suits teams that want unions, the faster SDK and the new library APIs and can upgrade again within two years.

Sources