
Learn how to use GitHub Copilot in Visual Studio for C# development. Setup, prompts, best practices, and pitfalls to code faster with AI today.
If you write C# for a living, GitHub Copilot in Visual Studio is no longer a novelty — it is one of the biggest productivity multipliers available to .NET developers in 2026. Microsoft reports that developers using Copilot complete routine tasks up to 55% faster, and in a C# codebase with its verbose boilerplate, strong typing, and predictable patterns, the AI has an unusually rich signal to work from. This guide explains how to set up GitHub Copilot in Visual Studio, how to use it well for C#, the best practices that separate a 10% gain from a 50% gain, and the pitfalls that can quietly hurt your code quality.
What Is GitHub Copilot and Why C# Developers Should Care
GitHub Copilot is an AI coding assistant built on large language models trained on public code and natural language. Inside Visual Studio it works in three main modes:
- Inline code completions — ghost-text suggestions that appear as you type, from a single line to whole methods.
- Copilot Chat — a conversational panel where you can ask questions about your code, generate tests, explain exceptions, or refactor a selection.
- Agent mode — a multi-step assistant that can edit several files, run builds, and iterate on compiler errors until a task is done.
Why does it work so well for C#? C# is statically typed, uses consistent naming conventions, and lives in a Visual Studio solution with full IntelliSense metadata. Copilot uses your open files, project references, and Roslyn semantic information as context, which means it suggests real method names from your own classes rather than hallucinating APIs. The more structured your code, the better the suggestions.
How to Set Up GitHub Copilot in Visual Studio
Setup takes about five minutes:
- Visual Studio 2022 17.10 or later (or Visual Studio 2026) ships with GitHub Copilot built in — no separate extension is required. Go to Tools → Options → GitHub → Copilot to confirm it is enabled.
- Sign in with a GitHub account under File → Account Settings. Copilot Free gives a limited number of completions and chat messages per month; Copilot Pro, Business, or Enterprise unlock unlimited use and premium models.
- Look for the Copilot icon in the top-right of the IDE. Green means active; a warning icon means you need to sign in or your subscription has lapsed.
- Open Copilot Chat with Ctrl+\, C or via View → GitHub Copilot Chat.
For team environments, administrators can enable content exclusions so that files such as appsettings.Production.json or secrets folders are never sent as context.
Inline Completions: Writing C# Faster
The fastest win is inline completion. Copilot reads what you have written and predicts what comes next. Its accuracy depends heavily on the intent you make visible — method names, parameter names, XML doc comments, and nearby code.
Consider a typical repository method. Type only the signature and a comment:
/// <summary>
/// Returns active customers who placed an order in the last N days,
/// ordered by total spend descending.
/// </summary>
public async Task<IReadOnlyList<CustomerSummary>> GetTopRecentCustomersAsync(
int days, int take, CancellationToken ct = default)
{
Copilot will typically propose a complete, idiomatic implementation like this:
var since = DateTime.UtcNow.AddDays(-days);
return await _db.Customers
.Where(c => c.IsActive && c.Orders.Any(o => o.CreatedUtc >= since))
.Select(c => new CustomerSummary(
c.Id,
c.Name,
c.Orders.Where(o => o.CreatedUtc >= since).Sum(o => o.Total)))
.OrderByDescending(s => s.TotalSpend)
.Take(take)
.ToListAsync(ct);
}
Notice it inferred _db from your class, used the CancellationToken, and chose ToListAsync because Entity Framework Core is referenced in the project. Press Tab to accept, Ctrl+Right Arrow to accept one word at a time, or Alt+. / Alt+, to cycle alternatives.
Tips for Better Inline Suggestions
- Name things precisely.
CalculateInvoiceTotalWithTaxgets a far better completion thanCalc. - Keep related files open. Copilot prioritises open tabs as context. Open the model class and interface before implementing a service.
- Write the test first. A failing xUnit test in an open tab is one of the strongest hints you can give.
- Use comments as micro-prompts. A one-line comment such as
// retry up to 3 times with exponential backoffreliably produces the right loop.
Copilot Chat: Explaining, Refactoring and Testing C# Code
Copilot Chat in Visual Studio is where the deeper productivity gains live. It understands slash commands and context references:
/explain— explains the selected code or an exception in the Error List./fix— proposes a fix for a compiler error or the highlighted code./tests— generates unit tests for the selected method./optimize— suggests performance improvements.#file,#solution,#method— reference specific context explicitly.
Say you select this legacy method and type "/optimize this for large collections and make it async":
public List<string> GetOverdueEmails(List<Invoice> invoices)
{
var result = new List<string>();
foreach (var invoice in invoices)
{
if (invoice.DueDate < DateTime.Now && !invoice.IsPaid)
{
var customer = _customerRepo.GetById(invoice.CustomerId);
if (!result.Contains(customer.Email))
result.Add(customer.Email);
}
}
return result;
}
A typical Copilot response identifies the N+1 lookup and the O(n²) Contains call, then rewrites it:
public async Task<IReadOnlyCollection<string>> GetOverdueEmailsAsync(
IEnumerable<Invoice> invoices, CancellationToken ct = default)
{
var now = DateTime.UtcNow;
var overdueCustomerIds = invoices
.Where(i => !i.IsPaid && i.DueDate < now)
.Select(i => i.CustomerId)
.Distinct()
.ToList();
if (overdueCustomerIds.Count == 0)
return Array.Empty<string>();
var customers = await _customerRepo.GetByIdsAsync(overdueCustomerIds, ct);
return customers
.Select(c => c.Email)
.Where(e => !string.IsNullOrWhiteSpace(e))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
This is the real value: Copilot does not just type faster, it surfaces improvements you might have missed at 4 pm on a Friday. Your job is to verify — for instance, confirm that GetByIdsAsync actually exists on your repository, or ask Copilot to add it.
Generating Unit Tests
Select a method, type /tests, and Copilot generates an xUnit, NUnit, or MSTest class based on the framework already in your solution. Example output for a discount calculator:
public class DiscountCalculatorTests
{
private readonly DiscountCalculator _sut = new();
[Theory]
[InlineData(100, 0, 100)]
[InlineData(100, 10, 90)]
[InlineData(100, 100, 0)]
public void Apply_ReturnsExpectedTotal(decimal price, decimal percent, decimal expected)
{
var result = _sut.Apply(price, percent);
Assert.Equal(expected, result);
}
[Theory]
[InlineData(-1)]
[InlineData(101)]
public void Apply_ThrowsForInvalidPercent(decimal percent)
{
Assert.Throws<ArgumentOutOfRangeException>(() => _sut.Apply(100, percent));
}
}
Always run the generated tests. Copilot occasionally asserts the behaviour it thinks the code has rather than what it actually does — a failing test is a useful signal either way.
Agent Mode: Multi-File Changes in Visual Studio
Agent mode (available in Visual Studio 2022 17.14+ and Visual Studio 2026) turns Copilot into an autonomous collaborator. Give it a task such as "Add a SoftDelete flag to the Product entity, create the EF Core migration, update the repository to filter deleted rows, and add tests". Copilot will:
- Plan the change and list the files it intends to edit.
- Apply edits across the entity, DbContext, repository, and test project.
- Run a build, read any compiler errors, and fix them iteratively.
- Present a diff for you to review and accept or reject per file.
Agent mode is powerful for scaffolding and mechanical refactors. It is less suited to subtle business logic, where your domain knowledge matters more than raw code generation. Treat its output like a pull request from a fast, enthusiastic junior developer: review every line.
GitHub Copilot Best Practices for C# Teams
1. Provide Context Deliberately
Add a .github/copilot-instructions.md file to your repository. Copilot reads it on every request. A practical C# example:
- Target .NET 10 and C# 14. Use file-scoped namespaces and primary constructors.
- All I/O methods must be async and accept a CancellationToken.
- Use xUnit with FluentAssertions for tests. Name tests Method_Scenario_Expected.
- Never use DateTime.Now; use TimeProvider or DateTime.UtcNow.
- Prefer records for DTOs and sealed classes by default.
This single file dramatically raises the consistency of suggestions across the whole team.
2. Review Like a Code Reviewer, Not a Typist
Accepted suggestions are your code. Check nullability, exception handling, thread safety, and disposal. Copilot frequently forgets using on HttpResponseMessage or SqlConnection, and sometimes swallows exceptions with an empty catch.
3. Use It for the Boring 80%
DTO mapping, argument validation, logging statements, regex patterns, LINQ queries, and test scaffolding are where Copilot shines. Keep architecture decisions and security-sensitive code (authentication, cryptography, SQL) under close human control.
4. Iterate in Chat
The first answer is rarely the best. Follow up with "make it thread-safe", "use Span<T> to avoid allocations", or "explain the trade-offs". Conversational refinement is faster than rewriting the prompt.
Common Pitfalls and How to Avoid Them
- Outdated APIs. Copilot may suggest
WebClient,BinaryFormatter, orThread.Sleepin async code. Enable analyzers (<AnalysisLevel>latest</AnalysisLevel>) so the compiler flags them. - Subtle logic errors. Off-by-one loops and inverted conditions look perfectly plausible. Tests are non-negotiable.
- Security issues. String-concatenated SQL and hard-coded connection strings can appear in suggestions. Use parameterised queries and configuration providers, and enable Copilot's built-in vulnerability filtering.
- Licensing. Enable the "block suggestions matching public code" setting if your organisation requires it.
- Skill atrophy. Beginners should periodically write code with Copilot disabled to make sure they still understand the fundamentals. Use
/explainas a learning tool rather than skipping comprehension. - Over-trusting agent mode. Large autonomous changes can introduce broad regressions. Keep tasks scoped, commit often, and review diffs file by file.
Conclusion: Key Takeaways
GitHub Copilot in Visual Studio can genuinely transform C# development when used with intent. The developers who get the most from it are not the ones who accept every suggestion — they are the ones who supply clear context, ask precise questions, and review rigorously.
- Copilot is built into Visual Studio 2022 17.10+ and Visual Studio 2026; sign in with GitHub and you are ready.
- Inline completions reward descriptive names, XML doc comments, and open related files.
- Copilot Chat commands like
/explain,/fix,/tests, and/optimizehandle the repetitive work so you can focus on design. - Agent mode is excellent for scaffolding and mechanical refactors — review every diff.
- A
copilot-instructions.mdfile plus enabled analyzers keeps AI-generated C# consistent and modern. - Never skip tests, nullability checks, or security review on generated code.
Start small: enable Copilot today, use it for tests and LINQ queries this week, and grow into chat and agent mode as you build trust. Used well, it is the most effective AI coding assistant for C# developers available right now.
Your go-to resource for C#, .NET, and modern software development. Follow along for daily tutorials, tips, and real-world examples.
Comments
Post a Comment