How I use AI for coding in C#

How I use AI for coding in C#

There are so many fantastic tools that ease the work of Software Engineers. While AI won’t replace for now, we can delegate a lot of work to it, saving us time to do more productive work.

Prompt engineering

You probaly heard this term before. It basically means the process of structuring text for text-based Generative AI models in order to make them more efficient and accurate.

I spent a night experimenting and made a prompt that is good enough to generate code by itself with only a little guidence. My goal is to minimize manual coding and writing commit messages as an extra. Suprisingly, the prompt and rules turned out to be easy, not complicated. Let me share it with you.

# The prompt, start the conversation with this

You are a coding bot integrated into Visual Studio.
File Modification:
    Request: I specify which file I want to modify and provide the changes needed.
    Response: You will provide the updated content for my review. You only respond with the updated code in the file and nothing else.
Next Steps:
    Request: I Specify the next task or modifications I want to implement in the project.
    Response: You will provide the updated content and wait for my feedback. The updated content is also only the code in the file.
Request format:
  1st line is a statement of filename.
  2nd line contains the requested modification to be applied to the file.
  3rd line instructs you to output the modified content and only that, only code. This makes sure you don't forget the instructions.

You can copy-paste this right into ChatGPT, OpenAI Playground or Azure OpenAI Studio. The expected behavior is when you request the change, GPT responds with code to instantly put into your IDE and compiles right away.

To achieve this you should go file-by-file, telling GPT what to change. It is important to tell GPT to only work on a single file at once. You should also instruct it to output the entire file with the existing code and the new modifications, unless it may just use lines of comments like “// Your existing code here” or “// Unchanged code here”. I don’t want that.

Request changes ✍

# Example 1: # Message to GPT on how to request changes to a particular file: open weatherforecastcontroller.cs add a new api that lists all cities with their current weather data output the entire weatherforecastcontroller.cs, only this file

Example1: The output was a complete code that I put right into Visual Studio.I was able to build without error and test instatly.

** Lines beginning with "#" are not part of the GPT prompt.

I changed code at one place and asked GPT apply to the rest 🤓

Similar prompt. I told GPT that I updated a file (because I wanted to introduce constants for attributes and logging). I input the entire codefile in triple quates (“””<code>”””), then instruct GPT to apply the changes to the other methods. GPT even introduced a new static class for the constants as it’s the best practice. Very nice! 👏

# Example 2: I updated weatherforecastcontroller.cs. new content:
"""
/* !! Unchanged code here (for article readibility) !! */
private const string _apiPath = "api/weatherforecast"; // Added
private const string _byCity = "bycity"; // Added

[HttpGet(_byCity, Name = "GetWeatherByCity")] // Modified
public ActionResult Get(string city)
{
var weatherData = _cityCoordinatesService.GetWeatherByCity(city);
if (weatherData != null)
{
_logger.LogInformation($"Successful HTTP/{nameof(Get).ToUpper()} on {_apiPath}/{_byCity}"); // Modified
return Ok(weatherData); // 200 OK response with weather data
}
_logger.LogInformation($"Unsuccessful HTTP/{nameof(Get).ToUpper()} on {_apiPath}/{_byCity}"); // Modified
return NotFound(); // 404 Not Found response when city coordinates are not found
}
/* !! Unchanged code here (for article readibility) !! */
"""
apply introduction of constants and logging for every method in the way I did
output weatherforecastcontroller.cs, only this file

Example 2: The output contained all the logger modifications I needed as well as a reference to a new static class called RouterConstants that coniained the required strings for the attributes. That class didn’t exist at this point, so I just asked to output it with a new message.

Best cases and tips 🍺

I also used the same concept of feeding the source code in triple quotes to fix errors. I also copied the compiler or runtime error messages along with the code. Also, when the output was’t sufficient enough, most of the time I only had to push the “replay” button to get another answer. If that didn’t work, I edited my prompt.

If you try it out yourself, I suggest you to only feed precise and possibly short change requests in each message. Otherwise you’ll get inconsistent output. I also suggest you feed the manually code again. ChatGPT will remember and will use the updated content for the next requests. You may also want to try this on the OpenAI Playground, so you can take adventage of the File and Assistant APIs. Assistants can read the source files that you upload, are able to read multiple of them at once which is supoer useful in some scenarios.

What’s next?

I’m now building a Visual Studio extension tool for everyone to seamlessly integrate this mechanism into their workflow. The extension will be open source, free software. 🤩

More on this later!

Stay focused, stay curious. Happy coding!

Leave a Reply

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