How to Use GitHub Copilot in Visual Studio for .NET Development (2026 Guide)

·

·

Most developers who try GitHub Copilot use it for a week, get a few useful autocompletes, then mostly forget it’s there. That’s leaving most of its value on the table. Copilot in Visual Studio 2022 has a Copilot Chat panel, slash commands, a multi-file edits mode, test generation, commit message generation, and context-aware suggestions that understand your entire codebase — not just the current file.

This guide is for .NET developers who want to actually use Copilot as a productivity tool, not just a fancy IntelliSense.

Table of Contents

Setup and Subscription

Requirements

  • Visual Studio 2022 version 17.10 or later (17.12+ recommended for Copilot Edits)
  • GitHub Copilot subscription: Individual ($10/mo), Business ($19/user/mo), or Enterprise ($39/user/mo)
  • GitHub account signed into Visual Studio

Installing in Visual Studio

  1. Visual Studio Installer → Modify → Individual Components → search “GitHub Copilot”
  2. Or: Extensions → Manage Extensions → search “GitHub Copilot”
  3. Sign in: View → GitHub Copilot → Sign In

Verifying It’s Working

Open any .cs file, start typing a method, and you should see gray ghost text appearing within 1–2 seconds. If you see nothing, check the Copilot status icon in the bottom-right status bar — it shows active/inactive state and any error messages.

Inline Completions: Getting the Most Out of Tab

Inline completions are Copilot’s most visible feature but most developers use them at 20% of their potential.

The Core Shortcuts

  • Tab — accept the full suggestion
  • Ctrl+ — accept word by word (don’t accept code you haven’t read)
  • Esc — dismiss
  • Alt+] / Alt+[ — cycle through alternative suggestions
  • Ctrl+Alt+\ — trigger completions manually

Writing Better Comments to Guide Completions

Copilot generates better code when you write a precise comment first:

// Bad comment — vague
// Get products
public async Task GetProducts() { }

// Good comment — Copilot generates correct signature and implementation
// Returns paginated products filtered by category, sorted by price ascending.
// Returns empty list if category has no products. Never returns null.
public async Task<PagedResult<Product>> GetProductsByCategoryAsync(
    string category,
    int page = 1,
    int pageSize = 20,
    CancellationToken cancellationToken = default)
{
    // Copilot will generate a solid implementation from here
}

Pattern Completion

Copilot learns from patterns in your current file. Write one implementation and let it complete the next:

// Write first case manually
public static string GetStatusLabel(OrderStatus status) => status switch
{
    OrderStatus.Pending => "Awaiting confirmation",
    OrderStatus.Processing => "Being prepared",
    // Tab here — Copilot completes remaining enum cases based on the pattern
};

Copilot Chat: Your In-IDE AI Assistant

Open Copilot Chat: Ctrl+Alt+I or View → GitHub Copilot Chat.

Chat vs Inline Chat

  • Copilot Chat panel — side panel for longer conversations, architecture questions, multi-step tasks
  • Inline ChatAlt+/ while text is selected — asks Copilot about the selected code without leaving your editor

Effective Chat Prompting for .NET

// In Copilot Chat panel:

// ✅ Good — specific, context-rich
"This EF Core query is slow on large datasets. The Products table has 500k rows.
 Suggest indexing strategy and query optimization options for this LINQ query:
 [paste query]"

// ✅ Good — asks for explanation, not just code
"Explain why this async method could cause a deadlock in an ASP.NET Core context,
 and show the fix: [paste method]"

// ❌ Too vague
"make this better"
"why is this not working"

Referencing Files in Chat

Type # in the chat box to reference specific files, methods, or symbols from your solution:

  • #file:ProductService.cs — include a file as context
  • #sym:IProductRepository — reference a specific symbol
  • #solution — include solution-level context (use sparingly — large context)

Slash Commands You Should Know

Type / in the Copilot Chat input to see all slash commands. The most useful for .NET developers:

/explain

// Select code → right-click → Copilot → Explain This
// Or in chat:
/explain #file:AuthenticationService.cs

// Copilot explains the selected code in plain English
// Useful for: understanding legacy code, onboarding, code reviews

/fix

// Select broken code or an error message → /fix
/fix The NullReferenceException on line 42 of UserController.cs

// Copilot identifies the bug and suggests a targeted fix
// More useful than /explain for active debugging

/tests

// Select a method or class → /tests
/tests #sym:OrderService.PlaceOrderAsync

// Generates xUnit/NUnit/MSTest tests (detects your test framework)
// See the Test Generation section for full workflow

/doc

// Select a method → /doc
/doc

// Generates XML documentation comments
/// <summary>
/// Places an order for the specified customer with the given items.
/// </summary>
/// <param name="request">The order placement request containing customer and item details.</param>
/// <returns>The created order with assigned ID and estimated delivery date.</returns>
/// <exception cref="InsufficientInventoryException">Thrown when items are out of stock.</exception>

/new

// Creates new files — useful for scaffolding
/new Create a repository interface and implementation for the Order entity using EF Core,
     following the pattern in #file:ProductRepository.cs

Copilot Edits: Multi-File Changes

Copilot Edits (VS 2022 17.12+) applies changes across multiple files simultaneously — like asking a developer to “implement this feature” and having them touch all the relevant files.

Starting an Edits Session

  1. Open Copilot Chat → click “Edits” tab (or Ctrl+Shift+I)
  2. Add files to the working set by clicking + or dragging from Solution Explorer
  3. Describe what you want — be specific

Effective Edits Prompts

// Example Edits prompt — specific and scoped
"Add soft delete support to the Product entity.
 1. Add IsDeleted and DeletedAt properties to Product.cs
 2. Add a migration for the new columns
 3. Update ProductRepository.cs to filter out soft-deleted items in all query methods
 4. Add a SoftDelete method to IProductRepository and ProductRepository
 5. Update ProductService.cs to call SoftDelete instead of hard delete"

// Copilot makes coordinated changes across all listed files
// Review each diff before accepting

Reviewing and Accepting Edits

Each file change shows as a diff — accept individual files or all at once. Use Ctrl+Z to undo accepted changes. Always review before accepting — Copilot can make reasonable-looking but incorrect changes, especially in complex codebases.

Generating Unit Tests

Test generation is one of Copilot’s most practical capabilities for .NET developers.

// Right-click on method → Copilot → Generate Tests
// Or: select method → /tests in chat

// Example output for OrderService.PlaceOrderAsync:
[Fact]
public async Task PlaceOrderAsync_ValidRequest_ReturnsCreatedOrder()
{
    // Arrange
    var mockRepo = new Mock<IOrderRepository>();
    var mockInventory = new Mock<IInventoryService>();
    var mockEmail = new Mock<IEmailService>();

    var request = new PlaceOrderRequest
    {
        CustomerId = 1,
        Items = new[] { new OrderItem { ProductId = 10, Quantity = 2 } }
    };

    mockInventory.Setup(i => i.CheckAvailabilityAsync(It.IsAny<int>(), It.IsAny<int>()))
                 .ReturnsAsync(true);

    var service = new OrderService(mockRepo.Object, mockInventory.Object, mockEmail.Object);

    // Act
    var result = await service.PlaceOrderAsync(request);

    // Assert
    Assert.NotNull(result);
    Assert.Equal(request.CustomerId, result.CustomerId);
    mockRepo.Verify(r => r.SaveAsync(It.IsAny<Order>()), Times.Once);
}

[Fact]
public async Task PlaceOrderAsync_InsufficientInventory_ThrowsException()
{
    // ... generated exception test
}

Improving Generated Tests

Generated tests are a starting point. Common improvements needed:

  • Add edge cases Copilot missed (null inputs, boundary values)
  • Verify the right mock methods were called with Verify()
  • Replace magic values with named constants
  • Add [Theory] with [InlineData] for parameterized cases

Refactoring Workflows

Extracting Interfaces

// Select a class → Copilot Chat:
"Extract an interface from this class that includes all public methods.
 Name it IProductService. Follow the naming conventions in #file:IOrderService.cs"

Applying Design Patterns

"Refactor this switch statement that creates different notification senders
 into a Strategy pattern. Use dependency injection to register strategies."

Converting to MVVM

"Convert this code-behind event handler to an MVVM pattern using
 CommunityToolkit.Mvvm. Create a ViewModel class with the appropriate
 [ObservableProperty] and [RelayCommand] attributes."

C# and .NET Specific Tips

Prompts That Work Well for .NET

  • “Add XML documentation to all public members in this class”
  • “Convert this method to use async/await instead of Task.Result”
  • “Add null checks and argument validation to this method following standard .NET patterns”
  • “Rewrite this LINQ query to avoid multiple enumeration”
  • “Add cancellation token support to this async method chain”
  • “Convert this class to use primary constructor syntax (C# 12+)”
  • “Add the [ObservableProperty] attribute from CommunityToolkit.Mvvm to this ViewModel”

EF Core Queries

// Ask Copilot to explain query performance
"Will this EF Core query cause N+1 selects? If so, rewrite it to avoid the problem:
 [paste query]"

// Ask for query optimization
"This query runs slow. Suggest indexes and rewrite the LINQ if needed.
 The database is SQL Server with 1M rows in Orders and 500 rows in Customers."

Making Copilot Context-Aware

Copilot’s suggestions improve dramatically when it has good context about your project.

Keep Related Files Open

Copilot uses open editor tabs as context. When working on OrderService.cs, keep IOrderService.cs, Order.cs, and IOrderRepository.cs open in tabs — Copilot will generate code consistent with those interfaces and types.

Use .github/copilot-instructions.md

Add a file at .github/copilot-instructions.md in your repo to set project-wide context:

# Copilot Instructions

## Project Context
This is a .NET 10 ASP.NET Core REST API for an e-commerce platform.

## Coding Standards
- Use CommunityToolkit.Mvvm for all ViewModels
- All async methods must accept CancellationToken
- Use Result pattern (not exceptions) for domain errors
- Repositories return IQueryable for LINQ composition
- All entities implement IAuditableEntity (CreatedAt, UpdatedAt, CreatedBy)

## Naming Conventions
- Interfaces prefixed with I (IOrderService)
- DTOs suffixed with Dto (CreateOrderDto)
- Commands suffixed with Command (PlaceOrderCommand)

## Test Framework
- xUnit with FluentAssertions and Moq
- Integration tests use WebApplicationFactory
- Test method naming: MethodName_Scenario_ExpectedResult

FAQ

Does Copilot send my code to GitHub’s servers?

Yes — code context is sent to GitHub’s servers to generate completions. For Individual/Business plans, GitHub states it doesn’t use your code to train Copilot models. Enterprise plans offer additional data residency and privacy guarantees. Check your organization’s policy before using Copilot with sensitive proprietary code.

How do I stop Copilot from suggesting code that violates our patterns?

Use the .github/copilot-instructions.md file to specify patterns and conventions. Also keep canonical example files open in tabs so Copilot sees the patterns directly. Consistently rejecting bad suggestions does influence future completions within a session.

Is Copilot worth the subscription cost for a solo .NET developer?

For active development work: yes, at $10/month. Most developers report 20–40% productivity improvement for routine coding tasks (CRUD endpoints, test boilerplate, documentation). If you mostly maintain rather than write new code, the value is lower.

Can Copilot help with .NET MAUI development?

Yes — Copilot understands MAUI-specific patterns including XAML bindings, CommunityToolkit.Mvvm attributes, Shell navigation, and platform-specific code. It’s particularly helpful for generating XAML templates and ViewModel boilerplate.

What’s the difference between Copilot Individual and Copilot Enterprise?

Enterprise adds indexing of your entire codebase (Copilot knows all files, not just open ones), custom fine-tuning on your code, knowledge bases (attach internal docs), and stronger privacy guarantees. Worth it for teams of 10+; overkill for solo developers.

Conclusion

GitHub Copilot’s value for .NET developers compounds with usage. The developers who get the most out of it treat it like a pair programmer — giving it context through comments, keeping relevant files open, and using Chat for complex tasks rather than just hoping inline completions get it right.

Start with inline completions, build the habit of writing precise comments, then graduate to Copilot Chat for refactoring and test generation. Once Edits mode feels natural, you’ll find yourself delegating multi-file feature scaffolding to Copilot as a first step.

[INTERNAL_LINK: Microsoft.Extensions.AI for .NET developers] [INTERNAL_LINK: MVVM in .NET MAUI with CommunityToolkit.Mvvm]


Leave a Reply

Your email address will not be published. Required fields are marked *