Blog

Smarter Refactoring Starts with GitHub Copilot Edits

By Randy Pagels

Randy Pagels

November 20, 2025
16 minutes

Introduction

Refactoring is a routine part of a developer’s job. Over time, projects accumulate code that works but could be cleaner, faster, or easier to maintain. Sometimes this is due to shifting requirements, other times it comes from rushed deadlines or inherited legacy code. Whatever the cause, improving the structure of existing code without changing its behavior is essential for keeping software healthy.

The challenge is that refactoring is often tedious. It requires scanning multiple files, understanding the dependencies, and making sure the changes don’t break anything. Even a relatively small improvement can pull you into a rabbit hole of related updates. This is where GitHub Copilot Edit Mode can make a noticeable difference.

Edit Mode acts like a skilled pair programmer sitting next to you, applying focused changes directly to your code based on a short instruction. Instead of typing everything yourself or bouncing between a chat window and the editor, you tell GitHub Copilot what you want, and it modifies the code in place. The result is a tighter feedback loop that keeps you in flow.

In the Wright Brothers aviation-themed sample project we will use throughout this article, Edit Mode will help us modernize backend C# controllers, improve code organization, and even generate reusable UI elements. By the end, you will see how this feature can shorten the path from “I need to fix this” to “done and tested” while still keeping you in control of the code.

What is GitHub Copilot Edit Mode?

GitHub Copilot Edit Mode is a way to apply AI-driven changes directly to your source code without leaving the editor. Instead of suggesting code completions line by line, it modifies the selected code block, file, or even multiple files in response to a short instruction you give it. This keeps the workflow focused on the code itself, rather than on a separate chat thread.

When you activate GitHub Copilot Edit Mode in VS Code, you:

  1. Select the code you want to modify, or leave nothing selected to target the whole file.
  2. Open the GitHub Copilot Chat sidebar or use the in-editor inline prompt (press Cmd+I on Mac or Ctrl+I on Windows/Linux, or right-click and select "Copilot: Inline Chat").
  3. Describe the change you want, such as “convert these methods to async/await” or “add XML documentation to this model.”
  4. The tool rewrites the code in place, keeping the rest of the file untouched unless the change requires broader adjustments.

How GitHub Copilot Edit Mode Works Under the Hood

Edit Mode uses the same underlying AI models as other GitHub Copilot features, but its output is designed for direct code replacement. It sends the relevant code context along with your request to the model (for example, GPT-4.1 or GPT-5), then generates the modified version. You review the diff before accepting the changes, similar to reviewing a pull request.

How It Differs from Ask Mode and Agent Mode

While all three modes are part of the GitHub Copilot Chat experience, each serves a different purpose:

  • Ask Mode is conversational. You can ask questions about the code, request examples, or get explanations. It doesn’t automatically apply changes, so it’s better for exploration or research.
  • Edit Mode applies targeted modifications directly to your code. It’s best for making specific, bounded changes you can review quickly.
  • Agent Mode takes a broader, more autonomous role. It can chain together multiple steps, create new files, run commands, or perform more complex tasks over time.

In short, GitHub Copilot Edit Mode is the “surgical tool” of the three. It’s designed for moments when you know what you want changed and want it applied without unnecessary steps.

When to Use Each Mode

Each mode in GitHub Copilot Chat is built for a different type of task. Choosing the right one helps you get results faster and with fewer edits afterward.

When to Use GitHub Copilot Ask Mode

Ask Mode is conversational and better for open-ended exploration or when you need guidance before making changes.

When to Use GitHub Copilot Edit Mode

Edit Mode is best when you know exactly what needs to change and the scope is contained. It’s ideal for:

  • Refactoring code without changing behavior.
  • Adding or improving documentation.
  • Making stylistic or formatting adjustments.
  • Extracting or moving code to improve structure.

When to Use GitHub Copilot Agent Mode

Agent Mode is the most autonomous. It’s suited for multi-file changes, creating new files, or performing coordinated updates.

Quick Decision Guide

  • Exploring or learning the code → Ask Mode
  • Clear on what to change and where → Edit Mode
  • Automating multi-step work → Agent Mode

Refactoring in Action: Wright Brothers Examples

Convert Backend Controller Methods to async/await

Scenario The FlightsController currently uses synchronous data access calls to retrieve and update flight information. This works, but under heavier load, synchronous calls can block threads and slow down the API. Converting these methods to use async/await allows requests to be processed more efficiently without blocking the thread pool.

Walkthrough

Start by opening FlightsController.cs. Highlight the synchronous methods that need to change, then use GitHub Copilot Edit Mode with a clear instruction like:

prompt Convert all of these methods to use async/await with Task return types, including updating service calls.

Review the suggested edits, confirm that async/await has been applied consistently, and run your integration tests to validate the change.

Summary

Edit Mode quickly applies a consistent async pattern across related methods, reducing manual work and risk of missed updates.

Extract Service Logic from a Controller

Scenario After converting the FlightsController to async/await, some business rules are still buried in the controller itself. For example, the AddFlight action might validate inputs, calculate an estimated arrival, and log activity before saving to the repository. Keeping all of that in the controller makes the code harder to maintain and test. Moving it into a FlightService class improves separation of concerns and keeps the controller focused on HTTP handling.

Walkthrough

Open FlightsController.cs and locate a method that mixes validation, calculations, and repository calls. Highlight the body of the method, then use GitHub Copilot Edit Mode with an instruction like:

prompt Move this logic into a new async method in FlightService called AddFlightAsync, and call it from here.

Review the generated changes. The controller method should now delegate to the service, while the FlightService contains the extracted logic. For example, the updated controller might look like this:

csharp public async Task<IActionResult> AddFlight(Flight flight) { var result = await _flightService.AddFlightAsync(flight); return result; }

And the new service method might include the validation and repository calls that were previously in the controller. At this point, run your tests. The functionality should remain the same, but the structure is improved: the controller is slimmer and the service owns the business rules.

Summary Separating concerns improves testability and keeps controllers lean. This is a strong use case for GitHub Copilot Edit Mode. With one focused instruction, you can move business logic into a proper service, making the code easier to test and maintain without manually rewriting each piece.

Add XML Documentation to a C# Model

Scenario The Wright Brothers project includes domain models like Plane, Pilot, Airfield, and Flight. They’re functional but undocumented. Without XML documentation, developers lose the benefit of IntelliSense tooltips, consistent API docs, and guidance for future maintainers. Adding structured comments makes the codebase easier to work with and more professional.

Walkthrough

Open Plane.cs and highlight the class along with its public properties. With the selection active, use GitHub Copilot Edit Mode and provide a clear instruction such as:

prompt Add XML documentation comments to this public class, its constructors, and all public properties. Use aviation terms like airframe hours and service ceiling where relevant. Keep summaries concise and under two sentences.

Review the suggested changes. GitHub Copilot will insert <summary> tags above the class, constructors, and properties. For example, the property ServiceCeilingFeet may get a comment like:

xml /// <summary> /// Certified service ceiling in feet above mean sea level. /// </summary> public int ServiceCeilingFeet { get; set; }

Skim through the generated comments to make sure the terminology matches your domain. If you use “tail number” instead of “registration,” or if you want shorter text in tooltips, adjust accordingly.

Summary

Edit Mode makes it easy to add consistent XML documentation in one pass, saving you from repetitive typing. You stay in control of the wording, but the tool handles the structure and formatting. Once you’re satisfied with the pattern, apply the same prompt to other models so your entire project follows a unified documentation style.

Build a Reusable Add Plane Button (React)

Scenario In many applications, you need a consistent way to trigger a backend operation from the UI. In the Wright Brothers project, that might mean adding a new plane to the fleet. Instead of duplicating fetch logic across pages, it’s cleaner to build a reusable AddPlaneButton React component. It can take optional defaults, handle network calls, and notify its parent when the new plane is created.

Walkthrough

Start by creating a new file, AddPlaneButton.tsx, in your components folder. With the empty file open, use GitHub Copilot Edit Mode and give it a clear prompt such as:

prompt Create a reusable React component named AddPlaneButton in TypeScript. Props: defaultRegistration?: string, defaultModel?: string, defaultYear?: number, onAdded?: (plane: Plane) => void. The button should post to /api/planes using fetch with JSON, disable itself while submitting, and show an error message if the request fails.

Review the output. GitHub Copilot will typically scaffold a functional component with useState for loading and error handling, plus a fetch call to the backend. At this point, refine the generated code with smaller, focused prompts. For example, if the button lacks accessibility features, highlight it and run:

prompt Improve accessibility by adding aria-busy while loading and aria-live="polite" for the error message.

If you want to keep the fetch logic separate from the UI, highlight the network code and use Edit Mode again:

prompt Extract the fetch call into a helper function createPlane(input: Partial<Plane>): Promise<Plane> in src/api/planes.ts. Import and use this helper in AddPlaneButton.

Finally, wire the onAdded callback so that any parent component using this button can refresh its state after a new plane is created. If GitHub Copilot didn’t include that in the first pass, highlight the click handler and ask:

prompt After a successful POST, if onAdded is provided, call onAdded with the created plane.

At this point, you have a reusable control that other pages can use without duplicating logic. Drop it into your planes list page, pass in defaults for registration or model if desired, and handle the onAdded callback to refresh the UI.

Summary Building a reusable UI control often takes more than one pass. With GitHub Copilot Edit Mode, it works best to scaffold the basics first, then refine in smaller, targeted iterations. One prompt handles the initial component, another improves accessibility, and another extracts helper logic. This stepwise approach keeps the AI focused, avoids overwhelming it with a single massive request, and gives you tighter control over the edits. The end result is a clean, reusable component that fits smoothly into the rest of your project.

More Ways to Use Edit Mode

Not every use of Edit Mode requires a full walkthrough. Sometimes a single, targeted prompt is enough to modernize code or bring it in line with team standards. Here are two examples where one focused instruction can save you from repetitive edits.

Refactor a React Data Fetch to react-query

Scenario

A component in the Wright Brothers project fetches flights with useEffect and manual state management. This works, but it duplicates boilerplate and doesn’t benefit from caching.

Walkthrough

Open the component, highlight the useEffect block and its state variables, then run GitHub Copilot Edit Mode with a clear instruction such as:

prompt Replace this manual fetch logic with @tanstack/react-query useQuery. Create a flights query keyed by ["flights"] that fetches GET /api/flights. Remove local isLoading and error state in favor of useQuery results. Keep TypeScript types strict.

GitHub Copilot will swap out the fetch call for a useQuery hook and remove redundant state. Review the diff, confirm that the query key matches your caching strategy, and adjust type imports as needed.

Summary This type of targeted refactor is well suited to Edit Mode. Instead of rewriting fetch logic in multiple components, one precise prompt moves you to a modern, standardized approach.

Fix Frontend Lint Issues and Adopt Modern Rules

Scenario

After tightening ESLint rules, many files in the project no longer comply. Fixing these by hand is tedious, especially when it’s mostly repetitive syntax or formatting changes.

Walkthrough

Open a file with violations, highlight the entire file or specific sections, and ask GitHub Copilot Edit Mode to bring it into compliance. For example:

prompt Apply changes to satisfy eslint and typescript-eslint: - Convert implicit any to explicit types, - Replace default exports with named exports, - Fix react-hooks exhaustive-deps warnings by stabilizing callbacks or listing correct deps. Do not alter code behavior.

Copilot will clean up the code, replacing default exports, fixing dependency arrays, and adding type annotations where needed. Run your linter again and repeat in batches of files until the project is clean.

Summary Scoped fixes like lint cleanups are a great fit for Edit Mode. A well-phrased prompt can resolve dozens of violations in one pass, leaving you to review the changes instead of chasing down errors by hand.

Writing Effective Edit Prompts

GitHub Copilot Edit Mode will do exactly what you ask—but only if your request is clear and scoped. A vague prompt like “fix this” leaves too much room for interpretation, while a precise instruction produces results you can trust.

Walkthrough The most effective Edit Mode prompts usually do three things:

  1. State the goal and any constraints Tell the tool what outcome you expect, and what boundaries it must respect. Example:

Convert these synchronous methods to async/await with Task return types. Do not change method names or parameters. Follow existing naming conventions for async methods.

  1. Use the project’s language and domain If your project uses specific terms, include them so the output feels consistent. Example:

Add XML documentation to this class and its public members. Use aviation terms like airframe hours and service ceiling where relevant. Keep summaries under two sentences.

  1. Keep edits small and iterative Break down big changes into a series of smaller prompts. You’ll get cleaner diffs and more predictable results. Example sequence for a React refactor:
    • Replace manual fetch with react-query.
    • Extract API call into a helper.
    • Improve accessibility and error handling.

Summary

You don’t need a complicated formula for writing Edit Mode prompts. A clear goal, consistent language, and smaller, iterative passes are enough to make GitHub Copilot a reliable partner in refactoring.

How Edit Mode Fits into a Broader AI-assisted Workflow

Edit Mode shines when you pair it with the other parts of GitHub Copilot. Use Ask Mode to understand the problem, use Edit Mode to make precise changes, then bring in Agent Mode when you need coordinated updates across files or supporting tasks like tests and scripts.

Walkthrough 1. Start with Ask Mode to orient yourself. For example, ask how flight scheduling checks maintenance status in the Wright Brothers project. Let the explanation point you to the controller and service that matter. 2. Switch to Edit Mode once the scope is clear. Highlight the relevant method and request a focused change, such as validating that a plane has no active maintenance records before scheduling. Review the diff, run your tests, and commit. 3. Move to Agent Mode if the change has ripple effects. Have the agent add or update integration tests, adjust seed data, or touch related files like a client SDK. Let it run the steps, you still approve the changes.

Summary

Treat the modes as a relay. Ask Mode clarifies, Edit Mode applies the targeted change, Agent Mode scales it across the codebase. This keeps you fast without sacrificing control.

Limitations and Things to Watch Out For

GitHub Copilot Edit Mode is reliable when you give it the right context, but there are edges to respect. The following points help you avoid surprises.

Watch-outs

  • Scope awareness. The tool edits what you select or what is visible in context, related files are not changed unless you ask for them.
  • Hidden dependencies. A safe looking refactor can miss callers or side effects elsewhere. Search for references and run tests after accepting a diff.
  • Prompt shape. Too vague invites broad edits, too narrow leaves work unfinished. State the goal and constraints, then iterate.
  • Behavior drift. Requests like “refactor without changing behavior” still need scrutiny. Read the diff, especially around conditionals and error handling.
  • Model and size limits. Very large files or wide requests can exceed context limits. Split the work into smaller passes for predictable results.

Summary

Edit Mode is powerful, not magical. Select enough context, write clear instructions, review diffs, and run tests. Small, reviewable passes keep changes safe and maintainable.

Conclusion

Refactoring is the kind of work that’s easy to postpone but critical for keeping a project healthy. What GitHub Copilot Edit Mode offers is not a replacement for good engineering practice, but a sharper tool for doing it. Instead of rewriting the same code patterns by hand, you can frame the change you need, let the tool propose it, then review and test with your full attention.

Throughout the Wright Brothers project examples, Edit Mode showed its range: converting controllers to async/await, moving business rules into services, adding XML documentation, and building a reusable UI button. Each task started with a clear instruction and ended with a focused diff that was easy to accept or refine. Keeping the tedious parts short and predictable is the real value here.

The bigger picture is that Edit Mode belongs in a workflow alongside Ask Mode and Agent Mode. Ask Mode helps you understand what you’re about to change, Edit Mode applies it cleanly, and Agent Mode can take care of the surrounding work like tests and multi-file adjustments. Used together, they let you move quickly without losing confidence in your codebase.

Final thought: The power of Edit Mode isn’t in flashy one-liners or giant transformations. It’s in the rhythm of small, precise prompts that keep you moving forward without breaking flow. Treat it like a skilled teammate that you guide with context and clarity, and you’ll find refactoring becomes faster, safer, and something you are far less likely to put off.

Written by

Randy Pagels

I am a DevOps Architect and Trainer at Xebia USA. I lead and educate customers in designing and implementing solutions that adhere to industry standards and DevOps best practices.

Contact

Let’s discuss how we can support your journey.