Copilot  

How to Fix Coding Errors with Copilot

Introduction

Debugging code can be tricky, especially when you're just starting out or working with unfamiliar code. GitHub Copilot, an AI assistant in Visual Studio, can help you understand what’s wrong in your code and even suggest ways to fix it. In this article, we'll see how Copilot can make debugging easier and faster with real examples.

Copilot can help us debug the code and provide help with the errors and exceptions in the code. Not only can Copilot explain the reason for the errors and exceptions, but it also suggests possible solutions.

If you're new to programming or using some older code from the internet, Copilot can help fix and modernize it for you.

Let’s see this in action.

Create a C# Console Application in Visual Studio and add the following code. Let’s assume you copied this code from Google search.

public class DebugWithCopilot
{
    public static void Main(string[] args)
    {
        int param1Value = Int32.Parse(args[0]);
        List<string> authors = null;

        if (param1Value > 0)
            authors = new List<string>();

        authors.Add("Mahesh Chand");
    }
}

Let’s say you notice something on the following line and you are not sure about this code.

int param1Value = Int32.Parse(args[0]);

You can ask Copilot to check it out for you.

Param

Copilot reviews the code and answers this.

Copilot reviews

It also suggests updated code that handles non integer values of args[0].

Let’s set a breakpoint at the same line.

Breakpoint

During debugging, on the same line, I ask Copilot the following question and it answers that yes, there may be a problem with the code.

Debugging

It also suggested the updated code.

Here is the updated code.

public static void Main(string[] args)
{
    if (args.Length == 0)
    {
        Console.WriteLine("No arguments provided. Please provide an argument.");
        return; // Exit the method if no arguments are provided
    }

    int param1Value;
    // Attempt to parse the first argument as an integer
    if (!Int32.TryParse(args[0], out param1Value))
    {
        Console.WriteLine("The provided argument is not a valid integer.");
        return; // Exit the method if the argument is not a valid integer
    }

    List<String> authors = null;
    if (param1Value > 0)
    {
        authors = new List<String>();
        authors.Add("Mahesh Chand");
    }
    // Ensure authors is not null before attempting to use it
    if (authors != null)
    {
        // Safe to use authors here
    }
}

Copilot also explains the new code and suggests more questions related to the code, and suggests to modify further to handle other possible exceptions, and also suggest to add more related functionality to the program.

Preview

I select the first suggestion.

Suggestion

It explains and writes the updated code.

And as is obvious, the newly updated code is in detail.

Updated code

And of course, suggest more updates in the existing code, including adding a log to capture errors in the code.

If you click on the first link, How can I modify ‘GetAuthorNameByIndex’ to fetch author names from a database instead of a hardcoded array?, Copilot writes full ADO.NET code for you that just needs the connection string updated to your database.

We will see how to build a complete data-driven application using Copilot in the following section of this book.

Code Review Again

The first rule of building better software is never trusting your code no matter if it’s generated by Copilot. Since Copilot uses publicly available historical open-source code samples, it’s possible that the code written by Copilot is not up to date.

So, I ask Copilot to update my code to C# 12, the latest version of the language.

While Copilot updates the code but still thinks that C# 12 is in Preview. However, in reality, C# 12 has already been released.

Code Review

Copilot suggests several changes in the code.

Changes

I accept the changes.

Copilot explained the updated code.

Key Changes and Considerations

  1. Use of var: The use of var for local variable declaration is encouraged for readability, especially when the right-hand side of the declaration makes the type obvious.
  2. Nullable Reference Types: Marking the return type of GetAuthorNameByIndex as string? Explicitly indicates that the method can return null. This is part of C#'s nullable reference types feature, which helps developers write more null-safe code.
  3. Simplified Array Initialization: The array of authorNames is initialized using the new[] syntax, which is concise and clear.
  4. Pattern Matching: While the provided code snippet doesn't directly benefit from C# 9's pattern matching enhancements, keeping an eye on pattern matching improvements in C# 12 and beyond can help simplify certain conditional checks.
  5. Expression-bodied Members: For methods like GetAuthorNameByIndex that consist of a single expression, consider using expression-bodied members for conciseness. This has been available since C# 7 for methods.
  6. Top-level Statements: If your application's entry point (Main method) is straightforward, you could consider using top-level statements to reduce boilerplate code. However, since your Main method contains significant logic, it's appropriate to keep it as is.

Remember, the adoption of new language features should be balanced with the readability and maintainability of your code, especially in team environments where not all members may be familiar with the latest features.

Conclusion

GitHub Copilot is a great tool for helping you write better code and fix errors quickly. It not only explains problems but also gives helpful suggestions to improve your code. While it’s powerful, always double-check what it writes. Use it as a smart assistant, not a replacement for learning and understanding code.

Download Copilot eBook: Copilot Handbook for Students and Developers