Skip to main content

Fixed: "error CS0165: Use of unassigned local variable" When a C# Local Function Becomes a Delegate

· 12 min read
Jagdish Kumawat
Founder @ Dewiride

My C# console app stopped building with error CS0165: Use of unassigned local variable 'requestNumber', and the position it named didn't use the variable at all: it was where I passed a local function to a method. A local function that becomes a delegate needs every variable it reads to have a value at that point, even when the delegate runs much later. Declaring the variable above that statement fixed it.

What I Was Doing​

I was building a .NET 10 console app with a Microsoft Agent Framework agent that answers cooking questions from a family recipe book. The app built and ran. Then I wanted to see what the agent sends to the model, so I added IChatClient middleware: a local function, ShowRequestAsync, that prints a line for each request and counts the requests in a local variable, requestNumber. A local function is a function declared inside other code, here among the program's top-level statements, and it can use that code's local variables.

The statement that creates the agent hands ShowRequestAsync to the chat client builder's .Use(...) method as getResponseFunc. I declared the counter after that statement, right above the local function, to keep the two together:

Program.cs (as it was)
AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(new ChatClientAgentOptions
{
Name = "RecipeHelper",
ChatOptions = new ChatOptions
{
ModelId = "gpt-5.6-luna",
Instructions = "You help a family cook from their recipe book. Answer in plain text, without Markdown.",
},
AIContextProviders = [skills],
},
clientFactory: chatClient => chatClient.AsBuilder()
.Use(getResponseFunc: ShowRequestAsync, getStreamingResponseFunc: null)
.Build());

// IChatClient middleware: shows what each request to the model carries.
int requestNumber = 0;
async Task<ChatResponse> ShowRequestAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
IChatClient innerClient,
CancellationToken cancellationToken)
{
requestNumber++;
string tools = string.Join(", ", options?.Tools?.Select(tool => tool.Name) ?? []);
Console.WriteLine($"[request {requestNumber}] {messages.Count()} message(s), tools: {tools}");
if (requestNumber == 1)
{
Console.WriteLine("[request 1] instructions:");
Console.WriteLine(options?.Instructions);
}

return await innerClient.GetResponseAsync(messages, options, cancellationToken);
}

Use your own project endpoint and model deployment. skills, created higher up in the file, gives the agent its recipe book; it plays no part in this error.

The agent only runs further down, after the local function:

Program.cs (as it was, below the local function)
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync("What do I need to make pancakes?", session);
PrintCalls(response);
Console.WriteLine($"Answer: {response.Text}");

RunAsync sends the question to the model, and PrintCalls is a small helper that prints the tool calls and approval requests in the response.

What I Expected​

A clean build, then one line from the middleware for each request the agent sends. ShowRequestAsync only runs when the agent sends a request to the model, and that happens inside RunAsync, well after int requestNumber = 0;. By then the counter has a value.

What I Got​

The build failed, so nothing ran:

Terminal
dotnet run
Output
/Users/you/source/RecipeHelper/Program.cs(30,31): error CS0165: Use of unassigned local variable 'requestNumber'

The build failed. Fix the build errors and run again.

macOS-style terminal window titled Terminal — RecipeHelper where dotnet run fails with Program.cs(30,31): error CS0165: Use of unassigned local variable 'requestNumber', followed by The build failed. Fix the build errors and run again.

The position in the message, line 30, column 31, isn't a place that uses requestNumber. Line 30 of the file is .Use(getResponseFunc: ShowRequestAsync, getStreamingResponseFunc: null), and column 31 is where ShowRequestAsync starts on that line: the spot where the local function is handed to .Use(...). The lines inside ShowRequestAsync that read and change the counter got no error of their own.

What I Checked​

What happens at line 30, column 31. .Use(...) takes getResponseFunc as a delegate, an object that points at a function so other code can call it later. Its documentation in Microsoft.Extensions.AI 10.11.0 describes the parameter as a delegate that provides the implementation for GetResponseAsync. Writing the local function's name there, without calling it, converts ShowRequestAsync into that delegate type. So line 30 doesn't run the function: it creates a delegate that points at it.

What Microsoft's page on CS0165 says. The C# compiler doesn't allow the use of uninitialized variables. And: This error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not. That second sentence fits my case: my code did give the counter its value before the delegate ever ran.

What the C# language specification says about local functions. Its section 9.4.4.33, "Rules for variables in local functions", starts with Local functions are analyzed in the context of their parent method. There are two control flow paths that matter for local functions: function calls and delegate conversions. About conversions, it says: Delegate conversions have a control flow path to the local function body. Captured variables are definitely assigned for the body if they are definitely assigned before the conversion. requestNumber is a captured variable, a local variable of the surrounding code that the local function uses. "Definitely assigned" is the specification's term for "certain to have a value at this point". At line 30 the counter had none: it was declared four lines further down.

The rule on its own. To check the rule away from the agent, I wrote a small program that does the same thing, in a folder of its own. A local function Next adds one to a counter. It's assigned to a Func<int> variable, a delegate, before the counter is declared, and only called after:

counter.cs
// The local function becomes a delegate here, before count has a value.
Func<int> next = Next;
int count = 0;

Console.WriteLine(next());
Console.WriteLine(next());

int Next() => ++count;

dotnet run counter.cs builds and runs a single C# file without a project file, which Microsoft calls a file-based app (.NET 10 and later). Run it in a folder that has no .csproj: when a project file exists in the current folder, Microsoft's page notes, dotnet run counter.cs runs that project instead.

Terminal
dotnet run counter.cs
Output
/Users/you/source/Cs0165/counter.cs(2,18): error CS0165: Use of unassigned local variable 'count'

The build failed. Fix the build errors and run again.

The same error, and again it points at the conversion: line 2, column 18 is Next in Func<int> next = Next;, not the ++count that uses the variable.

Why It Happens​

C# doesn't check a local function's body once, where the function is declared. It checks it at each place the function is used. A call is checked at the call. A conversion to a delegate is checked at the conversion: the specification gives the conversion a control flow path into the function's body, as if the body could run right there. So every variable the function reads must already have a value at that point.

In my app, the conversion was at line 30 and int requestNumber = 0; came at line 34. That the delegate really ran much later, inside RunAsync, changes nothing: the compiler checks the conversion, not the moment the delegate runs.

Where the local function itself is declared doesn't matter. Microsoft's guide to local functions: You can declare a local function before or after the statements that call it.

The Fix​

Declare the counter, with its value, above the statement that converts the local function. A comment says why, so nobody moves it back while tidying the file:

Program.cs
// 2. Counts the requests the agent sends to the model. It's declared before the agent,
// because the agent's middleware uses it.
int requestNumber = 0;

AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(new ChatClientAgentOptions
{
Name = "RecipeHelper",
ChatOptions = new ChatOptions
{
ModelId = "gpt-5.6-luna",
Instructions = "You help a family cook from their recipe book. Answer in plain text, without Markdown.",
},
AIContextProviders = [skills],
},
clientFactory: chatClient => chatClient.AsBuilder()
.Use(getResponseFunc: ShowRequestAsync, getStreamingResponseFunc: null)
.Build());

AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync("What do I need to make pancakes?", session);
PrintCalls(response);
Console.WriteLine($"Answer: {response.Text}");

// IChatClient middleware: shows what each request to the model carries.
async Task<ChatResponse> ShowRequestAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
IChatClient innerClient,
CancellationToken cancellationToken)
{
requestNumber++;
string tools = string.Join(", ", options?.Tools?.Select(tool => tool.Name) ?? []);
Console.WriteLine($"[request {requestNumber}] {messages.Count()} message(s), tools: {tools}");
if (requestNumber == 1)
{
Console.WriteLine("[request 1] instructions:");
Console.WriteLine(options?.Instructions);
}

return await innerClient.GetResponseAsync(messages, options, cancellationToken);
}

macOS-style code window titled Program.cs — RecipeHelper showing int requestNumber = 0 declared first, under a comment saying it comes before the agent because the agent's middleware uses it, then the agent statement that passes ShowRequestAsync to Use, the lines that run the agent, and the ShowRequestAsync local function that adds one to requestNumber and prints each request.

Two things moved. int requestNumber = 0; now comes before the agent statement, so the counter has its value at the conversion, which is now on line 34. And the lines that run the agent moved up, above the local function, so the file reads in order: counter, agent, run, middleware. That second move is only for reading: in both versions, ShowRequestAsync is declared below the conversion.

The small program gets the same fix, with the counter first:

counter-fixed.cs
// count has a value before the local function becomes a delegate.
int count = 0;
Func<int> next = Next;

Console.WriteLine(next());
Console.WriteLine(next());

int Next() => ++count;
Terminal
dotnet run counter-fixed.cs
Output
1
2

It builds, and each call of the delegate adds one to the counter.

After the Fix​

Terminal
dotnet run
Output
[request 1] 1 message(s), tools: load_skill, read_skill_resource, run_skill_script
[request 1] instructions:
You help a family cook from their recipe book. Answer in plain text, without Markdown.

macOS-style terminal window titled Terminal — RecipeHelper where dotnet run now builds and the middleware prints its first lines for request 1: one message, the tools load_skill, read_skill_resource and run_skill_script, and the start of the agent's instructions.

The build passes and the middleware runs: those are the first lines of the output. After them come the rest of the instructions the agent sends with its first request, a line each for request 2 and request 3, then the agent's two tool calls and its answer about pancakes.

Common Mistakes​

MistakeWhat happensDo this instead
Declaring a variable that a local function reads below the statement that passes the function as a delegateerror CS0165 at the spot where the function is passedDeclare the variable, with its value, above that statement
Looking for the problem on the lines that use the variableThe message points at the conversion, not at a useFind the local function at the reported column and check which variables it reads
Moving the declaration back next to the local function while tidying the fileThe build fails again with the same errorLeave a comment above the declaration that says why it sits there

Troubleshooting​

SymptomLikely causeFix
error CS0165 at a local function's name passed to a methodA variable the function reads has no value yet at that pointDeclare and assign it before that statement
error CS0165 at a line like Func<int> next = Next;Assigning a local function to a delegate variable is a conversion tooAssign the variables the function reads first
The app's own output never appearsdotnet run stops when the build failsFix the error the build lists, then run again

FAQ​

Does it matter where the local function is declared?​

No. A local function can be declared before or after the code that uses it. What matters is whether the variables it reads have values at the point where it's called or converted to a delegate.

Is a direct call of the local function checked the same way?​

Yes, at the call. The specification: At each invocation, variables captured by the local function are considered definitely assigned if they were definitely assigned at the point of call. Its own example marks a call made before the variable has a value as an error.

Why doesn't the compiler see that the delegate only runs later?​

The rule doesn't look at when the delegate runs, only at the conversion. Microsoft's page on CS0165 says the error comes for any construct that might use an unassigned variable, even when your particular code doesn't, which avoids the necessity of overly complex rules for definite assignment.

Conclusion​

error CS0165: Use of unassigned local variable at the spot where a local function is passed as a delegate means a variable the function reads has no value yet at that point. C# checks a delegate conversion as if the function's body could run right there, whenever the delegate really runs. Declare the variable, with its value, before the statement that converts the function, and leave a comment that says why.

Additional Resources​

  • Compiler Error CS0165, on Microsoft Learn: what the error means, and why the compiler reports it even when your code wouldn't use the variable.
  • Rules for variables in local functions, section 9.4.4.33 of the C# language specification: how calls and delegate conversions are checked.
  • Local functions, on Microsoft Learn: declaring local functions and the variables they capture.
  • ChatClientBuilder.Use, on Microsoft Learn: the getResponseFunc delegate the middleware is passed as.
  • File-based apps, on Microsoft Learn: running a single C# file with dotnet run.