Back to blog

Using ChatGPT for C# Development

July 28, 20238 min read

How ChatGPT can help you write, refactor, and document C# code more effectively, with practical examples and integration strategies.

Using ChatGPT for C# Development

How do you integrate AI into your daily coding workflow without disrupting what already works? That's a question worth examining as tools like ChatGPT become more prevalent in software development.

In my experience working with C# projects, I've found ChatGPT useful alongside tools like GitHub Copilot and Stack Overflow, each serving different purposes. While not every response is perfect or immediately runnable, ChatGPT offers another perspective for approaching development challenges.

Related: See also my article on Trivia Spark: Igniting Creativity With ChatGPT for another practical AI integration example.

What is ChatGPT?

ChatGPT (Chat Generative Pre-trained Transformer) is a natural language processing model developed by OpenAI. It generates human-like responses to text input, trained on large datasets to understand language patterns and nuances.

The model can assist with various tasks including answering questions, composing emails and essays, and writing code. While some underlying technology is open source, the specific model and its parameters are proprietary and available only as a cloud-based service.

For more information, see the OpenAI Blog or the video overview below:

ChatGPT for C# Developers

What makes ChatGPT particularly useful for C# development? It can answer technical questions, provide context about development processes, and help improve productivity. Think of it as another tool in your toolkit rather than a replacement for existing resources.

Not every response will be correct or production-ready, but that's part of working with any AI tool. The value comes from how you integrate it into your workflow and verify its suggestions.

Real-World Examples

Let me share some practical ways I've used ChatGPT in C# projects. These examples show both the potential and the limitations worth considering.

Explaining Existing Code Blocks

Ever inherited a codebase with complex or undocumented logic? ChatGPT can help explain code blocks you don't fully understand, which is especially useful for legacy systems.

// Input:
// Can you explain this C# code to me?
public class MyClass
{
  public int Property { get; set; }
}

// Output:
// This code defines a class called "MyClass" with a single property called "Property".
// The property is of type "int" and is publicly accessible using the "get" and "set" accessors.

While this example is straightforward, the same approach works for more complex patterns like LINQ expressions, async/await patterns, or architectural components.

Improving Existing Code

ChatGPT can suggest modifications to improve code clarity and maintainability. Here's an example of refactoring for better readability:

// Original code
public void ProcessData(string data)
{
  if (data != null)
    Console.WriteLine(data);
}

// Suggested improvement
public void ProcessData(string data)
{
  if (data != null)
  {
    Console.WriteLine(data);
  }
}

The refactored version includes explicit code blocks and follows C# conventions more consistently. These small improvements add up across a large codebase.

Rewriting Code for Style

C# has well-established naming conventions, and ChatGPT can help align code with these standards:

// Input:
// Can you help me rewrite this code to follow C# naming conventions?
public class MyClass
{
  public int Prop { get; set; }
  public void Do_Something()
  {
    // Method body
  }
}

// Output:
public class MyClass
{
  public int Prop { get; set; }
  public void DoSomething()
  {
    // Method body
  }
}

Consistency in naming improves code readability and helps teams maintain shared standards.

Rewriting Code with Idiomatic Constructs

ChatGPT can refactor code to use more idiomatic C# patterns, making it more readable:

// Input:
// Can you help me rewrite this code to use C# idiomatic constructs?
public int SumArray(int[] array)
{
  int sum = 0;
  for (int i = 0; i < array.Length; i++)
  {
    sum += array[i];
  }
  return sum;
}

// Output:
public int SumArray(int[] array)
{
  int sum = 0;
  foreach (int element in array)
  {
    sum += element;
  }
  return sum;
}

Using idiomatic constructs like

foreach
instead of traditional
for
loops can make intent clearer. Though for simple summation, you might also consider LINQ's
Sum()
method.

Simplifying Existing Code

Sometimes there are more efficient or clearer ways to implement functionality. ChatGPT can suggest alternatives:

// Original approach
public bool IsPositive(int number)
{
  if (number > 0)
  {
    return true;
  }
  else
  {
    return false;
  }
}

// Simplified version
public bool IsPositive(int number)
{
  return number > 0;
}

These simplifications reduce noise and make the actual logic more apparent.

Writing Test Cases

Test coverage is critical but time-consuming. ChatGPT can generate test case scaffolds:

// Input: Generate test cases for this method
public int Add(int a, int b)
{
  return a + b;
}

// Output: ChatGPT generates test scaffolding
[TestClass]
public class CalculatorTests
{
  [TestMethod]
  public void Add_PositiveNumbers_ReturnsSum()
  {
    // Arrange
    int a = 5;
    int b = 3;
    
    // Act
    int result = Add(a, b);
    
    // Assert
    Assert.AreEqual(8, result);
  }
  
  [TestMethod]
  public void Add_NegativeNumbers_ReturnsSum()
  {
    // Arrange
    int a = -5;
    int b = -3;
    
    // Act
    int result = Add(a, b);
    
    // Assert
    Assert.AreEqual(-8, result);
  }
}

While you'll still need to review and expand these tests, having a starting structure saves time.

Writing Documentation

Documentation is essential but often neglected. ChatGPT can generate XML documentation comments:

// Input: Add XML documentation to this method
public int Divide(int numerator, int denominator)
{
  return numerator / denominator;
}

// Output:
/// <summary>
/// Divides two integers and returns the result.
/// </summary>
/// <param name="numerator">The number to be divided.</param>
/// <param name="denominator">The number to divide by.</param>
/// <returns>The quotient of the division.</returns>
/// <exception cref="DivideByZeroException">Thrown when denominator is zero.</exception>
public int Divide(int numerator, int denominator)
{
  if (denominator == 0)
  {
    throw new DivideByZeroException("Cannot divide by zero.");
  }
  return numerator / denominator;
}

Notice how it also identified the potential exception case that should be documented and handled.

Scaffolding Code

ChatGPT can generate code templates to speed up development:

// Input: Create a repository pattern for a User entity

// Output: Generated scaffold
public interface IUserRepository
{
  Task<User> GetByIdAsync(int id);
  Task<IEnumerable<User>> GetAllAsync();
  Task<User> AddAsync(User user);
  Task UpdateAsync(User user);
  Task DeleteAsync(int id);
}

public class UserRepository : IUserRepository
{
  private readonly DbContext _context;
  
  public UserRepository(DbContext context)
  {
    _context = context;
  }
  
  public async Task<User> GetByIdAsync(int id)
  {
    return await _context.Users.FindAsync(id);
  }
  
  // Additional methods...
}

The generated code provides a foundation that you can customize for your specific needs.

For more complex scenarios, ChatGPT can help with patterns like limiting concurrent REST calls using

SemaphoreSlim
and
Task.WhenAll
. These scaffolds save boilerplate writing time while maintaining consistent patterns.

Where Does This Lead?

As AI tools continue to evolve, their role in software development will likely expand. ChatGPT has proven useful for accelerating prototyping, improving code quality, and supporting continuous learning. But it works best when combined with developer judgment and verification.

What matters is finding the right balance—using AI to handle routine tasks while focusing your expertise on architecture, design decisions, and complex problem-solving.

For more on AI-assisted development approaches, check out my article on Trivia Spark: Igniting Creativity With ChatGPT.