34
Lesson 34 of 35 · Advanced

GitHub Copilot AI Coding

GitHub Copilot is an AI pair programmer built into Visual Studio 2026. It suggests whole lines and entire functions as you type, answers questions in natural language, and helps you debug, refactor, and write tests.

Enabling Copilot

Sign in to GitHub inside Visual Studio 2026 (Tools → GitHub → Sign In). Copilot requires a paid subscription or GitHub Education. Once connected, a Copilot icon appears in the status bar.

Inline Code Suggestions

As you type, Copilot shows ghost-text suggestions in grey. Press Tab to accept, Esc to dismiss, or Alt+] / Alt+[ to cycle through alternatives.

Copilot accepts a comment and generates code CopilotDemo.cs
// Sort a list of Employee objects by Salary descending, then by Name ascending
// ← Copilot generates the following when you press Enter:
var sorted = employees
    .OrderByDescending(e => e.Salary)
    .ThenBy(e => e.Name)
    .ToList();

// Parse a CSV line into a (string Name, int Age, double Score) tuple
// ← Copilot suggests:
static (string Name, int Age, double Score) ParseLine(string line)
{
    var parts = line.Split(',');
    return (parts[0].Trim(), int.Parse(parts[1]), double.Parse(parts[2]));
}

Copilot Chat

Open the Copilot Chat panel (View → GitHub Copilot Chat). Ask questions like: "Explain this method", "Find bugs in the selected code", "Write unit tests for this class", or "Refactor to use LINQ".

Best Practices

Write descriptive comments before the code you want Copilot to generate. Give it context by having the relevant classes open. Always review generated code critically—Copilot can produce plausible-but-wrong code. Use it for boilerplate, not architectural decisions.

Copilot with unit tests prompt CopilotTests.cs
// Generate xUnit tests for the BankAccount class covering:
// 1. Successful deposit increases balance
// 2. Withdrawal exceeding balance returns false
// 3. Negative deposit throws ArgumentException
// ← Copilot writes the full test class from this comment