Introduction
In the previous article, "How to Call the Claude API from C# (.NET): Build Your First AI Console App", we sent one question to Claude and printed the answer. That works, but it isn't a conversation yet. If you ask a follow-up like "Can you explain that again with an example?", Claude has no idea what "that" means.
In this article we will build a multi-turn chatbot in C# that:
- Remembers earlier messages in the conversation
- Uses a system prompt to give the bot a personality and rules
- Lets the user clear the memory with a command
- Shows token usage so you can keep an eye on cost
- Trims old messages so the conversation doesn't grow forever
No extra NuGet packages are needed: we only use HttpClient and System.Text.Json, which are part of .NET.
Prerequisites
- .NET 8 SDK or later
- A Claude API key from the Claude Console (console.anthropic.com)
- Any editor: Visual Studio, VS Code or Rider
How "memory" works in the Claude API
The Claude API is stateless. It does not store your chat on the server. Every time you call it, you send the full conversation so far as a list of messages:
[
{ "role": "user", "content": "What is LINQ?" },
{ "role": "assistant", "content": "LINQ is a way to query collections in C#..." },
{ "role": "user", "content": "Show me an example." }
]So "memory" simply means: keep a list in your app, add every user message and every Claude reply to it, and send the whole list each time. Messages must alternate between user and assistant, starting with user.
Step 1: Create the project
dotnet new console -n ClaudeChatBot
cd ClaudeChatBotStep 2: Store your API key safely
Never hard-code your API key in source code. Set it as an environment variable instead.
Windows (PowerShell):
setx ANTHROPIC_API_KEY "your-api-key-here"macOS / Linux:
export ANTHROPIC_API_KEY="your-api-key-here"Restart your terminal or IDE after setting it.
Step 3: Write the chatbot
Replace everything in Program.cs with the code below.
using System.Net.Http.Json;
using System.Text.Json.Serialization;
// 1. Read the API key from an environment variable
var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
?? throw new InvalidOperationException("Please set the ANTHROPIC_API_KEY environment variable.");
// 2. Configure HttpClient with the required Claude headers
using var http = new HttpClient { BaseAddress = new Uri("https://api.anthropic.com/") };
http.DefaultRequestHeaders.Add("x-api-key", apiKey);
http.DefaultRequestHeaders.Add("anthropic-version", "2026-10-21");
const string Model = "claude-sonnet-5-5";
const int MaxHistory = 20; // keep the last 20 messages (10 back-and-forth turns)
const string SystemPrompt =
"You are a friendly C# tutor. Explain things simply, use short code examples, " +
"and keep answers under 150 words unless the user asks for more.";
// 3. This list is the chatbot's memory
var history = new List<Message>();
Console.WriteLine("Claude C# Tutor - type 'exit' to quit or 'clear' to reset memory.\n");
while (true)
{
Console.Write("You: ");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input)) continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase)) break;
if (input.Equals("clear", StringComparison.OrdinalIgnoreCase))
{
history.Clear();
Console.WriteLine("(Memory cleared)\n");
continue;
}
// 4. Add the user's message to memory
history.Add(new Message("user", input));
// 5. Send the whole conversation to Claude
var request = new MessageRequest(Model, 1024, SystemPrompt, history);
var response = await http.PostAsJsonAsync("v1/messages", request);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
Console.WriteLine($"\nError {(int)response.StatusCode}: {error}\n");
history.RemoveAt(history.Count - 1); // undo the failed message
continue;
}
var result = await response.Content.ReadFromJsonAsync<MessageResponse>();
var reply = string.Concat(result!.Content
.Where(block => block.Type == "text")
.Select(block => block.Text));
// 6. Add Claude's reply to memory
history.Add(new Message("assistant", reply));
// 7. Trim old messages (remove in pairs so the list still starts with "user")
while (history.Count > MaxHistory)
{
history.RemoveRange(0, 2);
}
Console.WriteLine($"\nClaude: {reply}");
Console.WriteLine($"[tokens - input: {result.Usage.InputTokens}, output: {result.Usage.OutputTokens}]\n");
}
// ----- Request / response models -----
record Message(
[property: JsonPropertyName("role")] string Role,
[property: JsonPropertyName("content")] string Content);
record MessageRequest(
[property: JsonPropertyName("model")] string Model,
[property: JsonPropertyName("max_tokens")] int MaxTokens,
[property: JsonPropertyName("system")] string SystemPrompt,
[property: JsonPropertyName("messages")] List<Message> Messages);
record MessageResponse(
[property: JsonPropertyName("content")] List<ContentBlock> Content,
[property: JsonPropertyName("usage")] Usage Usage);
record ContentBlock(
[property: JsonPropertyName("type")] string Type,
[property: JsonPropertyName("text")] string? Text);
record Usage(
[property: JsonPropertyName("input_tokens")] int InputTokens,
[property: JsonPropertyName("output_tokens")] int OutputTokens);
Join the conversation! Your thoughts help the community grow.