Software Engineer Reviews C# Code Generated by ChatGPT
ChatGPT has been around for a few months. I have been using it for .NET development for a few weeks. Today, I ask ChatGPT to solve 3 C# programming tasks.
I am an experienced software developer with more than a decade of experience with the .NET platform, and I will judge the code generated by ChatGPT in detail.
Is ChatGPT good enough for C# development? Can it even replace software developers? Let’s find out.
Experiment 1: Generating Data Filtering Code
ChatGPT, please write a C# method that orders a list of Person objects by name and excludes all persons that are underage.
ChatGPT takes a few seconds and answers:
Sure! Here’s an example C# method that orders a list of Person objects by name and excludes all persons that are underage:
static List<Person> OrderAndFilterPeople(List<Person> people)
{
var filteredPeople = people.Where(p => p.Age >= 18).ToList();
var orderedPeople = filteredPeople.OrderBy(p => p.Name).ToList();
return orderedPeople;
}
We have a static method that returns a List of Person objects called OrderAndFilterPeople, accepting a single parameter of type List of Person.
Next, we use the LINQ method syntax to filter the persons in the people list by Age, and order them by name.
Judging from what I see, I do believe the code will give us the right result according to our query. However, I would probably implement the method differently. But let’s not get ahead of ourselves for now. We will copy the code over to Visual Studio in a minute.
Let’s read the explanation from ChatGPT first.
In this method, we first use LINQ’s Where method to filter out all persons that are underage. We do this by specifying a lambda expression that checks whether the person’s Age property is greater than or equal to 18.
Next, we use LINQ’s OrderBy method to order the remaining people by their Name property. We again use a lambda expression to specify the property to order by.
Finally, we return the ordered list of people.
Note that this method assumes that the Person class has properties called Name and Age. You may need to adjust the code accordingly to match your specific implementation of the Person class.
Well, if ChatGPT even tells us what the Person class should look like, what about if we ask it to write it for us?
Can you also add a simple C# class for the Person, including a name, age, and date of birth?
Certainly! Here’s an example Person class in C# that includes a Name, Age, and DateOfBirth property:
public class Person
{
public string Name { get; set; }
public int Age
{
get { return CalculateAge(DateOfBirth); }
}
public DateTime DateOfBirth { get; set; }
private static int CalculateAge(DateTime dateOfBirth)
{
int age = DateTime.Now.Year - dateOfBirth.Year;
if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
{
age--;
}
return age;
}
}
From what I can tell, this class looks okay. It even implemented a calculated Age property based on the current date and the date of birth of the Person.
Let’s read the explanation next.
In this implementation, the Person class has a Name property, a DateOfBirth property, and a calculated Age property. The Age property calculates the person’s age based on their DateOfBirth property using a private CalculateAge method.
Note that this implementation assumes that the person’s age is calculated based on the current date and time. If you need to calculate their age based on a specific date or time zone, you’ll need to adjust the code accordingly.
It looks like we could go on and on and further enhance this code by generating code using ChatGPT. However, let’s see if the code actually works and what an experienced .NET developer would maybe do differently.
Let’s jump into Visual Studio.
I copied the two code snippets generated by ChatGPT into a console application in Visual Studio. We can already see a compiler error because we need to wrap methods into a class within the Program.cs file.
ChatGPT isn’t aware of the context where this code will be used, so that’s fine, and I wrap a class called PeopleFilter around the method.
Next, we get the compiler error that the Program does not contain a static ‘Main’ method. It’s because we’re missing top-level statements that will be shifted into the Main method of the console application.
Let’s change that by creating a people list and adding a Person to the list. We want to run the code anyways, so we need that data.
We also call the OrderAndFilterPeople method, save the resulting collection to a variable and use a foreach to loop through all the person objects to output the name followed by the age.
For a simple test to see if underage persons are excluded, I add another person born in 2015.
Let’s start the Program to see the result.
As you can see, the program correctly filters the list of persons according to the rules we gave ChatGPT.
Now, let’s see what the implementation looks like and what changes I would make. First of all, let’s look at the OrderAndFilterPeople method. I would shorten the implementation to a single return statement followed by chaining the OrderBy method onto the Where method. We can also remove an unnecessary ToList call between both methods.
static List<Person> OrderAndFilterPeople(List<Person> people)
{
int legalAge = 18;
return people
.Where(p => p.Age >= legalAge)
.OrderBy(p => p.Name)
.ToList();
}
The Person class looks good to me. We could add a constructor, but the structure of the class makes sense to me as it was generated by ChatGPT.
The CalculateAge method called within the Age property is interesting. The implementation is correct and makes sense. It even considers if the person’s birthday is already passed in the current year.
I would probably inline the code into the getter of the Age property, but that’s my personal preference. I’m pretty happy and impressed with what ChatGPT produced for this example.
Experiment 2: Sorting Algorithms
Let’s try something more algorithmic for the second example. I ask ChatGPT:
Can you please implement a method in C# with 52 values in an array, shuffles the items, and returns a random value from the array?
Sure, here’s a sample method in C# that shuffles the elements of an array of 52 values and returns a random value from the array.
I like how ChatGPT states what it does, so we have a chance to see if it may be misunderstood our query.
public static int GetRandomCard()
{
int[] deck = new int[52];
for (int i = 0; i < deck.Length; i++)
{
deck[i] = i;
}
Random rand = new Random();
for (int i = 0; i < deck.Length; i++)
{
int j = rand.Next(i, deck.Length);
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
int randomCardIndex = rand.Next(0, deck.Length);
int randomCard = deck[randomCardIndex];
return randomCard;
}
The generated code looks good so far. Apparently, ChatGPT thinks we want to implement a card game because I choose 52 as the number of items in the array.
This method creates an array deck of size 52 and initializes it with values from 0 to 51. It then shuffles the elements of the array using the Fisher-Yates shuffle algorithm. Finally, it selects a random index within the range of the array and returns the value at that index.
You can call this method in your program to get a random card as follows.
Chat GPT even gives us the code to call the method to create a random value. It even tells us that each call to the method will yield a different result.
I’m not happy with how everything looks like we wanted to implement a card game. I, therefore, ask ChatGPT to increase the size of the array to 100 and to use random first names instead of integer values for the array.
public static string GetRandomName()
{
string[] names = new string[]
{
"Emma", "Liam", "Olivia", "Noah", "Ava", "William", "Sophia", "James", "Isabella", "Oliver",
"Mia", "Benjamin", "Charlotte", "Elijah", "Amelia", "Lucas", "Evelyn", "Mason", "Abigail", "Logan",
"Harper", "Alexander", "Emily", "Ethan", "Elizabeth", "Jacob", "Mila", "Michael", "Ella", "Daniel",
"Avery", "Henry", "Sofia", "Jackson", "Camila", "Sebastian", "Aria", "Aiden", "Scarlett", "Matthew",
"Victoria", "Samuel", "Madison", "David", "Luna", "Joseph", "Grace", "Carter", "Chloe", "Owen",
"Penelope", "Wyatt", "Lily", "John", "Nora", "Jack", "Aubrey", "Luke", "Ellie", "Jayden",
"Stella", "Dylan", "Paisley", "Grayson", "Audrey", "Levi", "Hazel", "Isaac", "Savannah", "Lincoln",
"Aaliyah", "Nicholas", "Addison", "Gabriel", "Skylar", "Julian", "Bella", "Christopher", "Lucy", "Joshua",
"Nova", "Andrew", "Brooklyn", "Theodore", "Genesis", "Ryan", "Naomi", "Nathan", "Alyssa", "Eli",
"Elena", "Isaiah", "Violet", "Hunter", "Eleanor", "Caleb", "Emilia", "Landon", "Eliana", "Christian"
};
Random rand = new Random();
for (int i = 0; i < names.Length; i++)
{
int j = rand.Next(i, names.Length);
string temp = names[i];
names[i] = names[j];
names[j] = temp;
}
int randomNameIndex = rand.Next(0, names.Length);
string randomName = names[randomNameIndex];
return randomName;
}
ChatGPT changes the code to use names instead of numbers and changes the identifiers from deck and card to names. Also, the name of the method changed.
I have to admit I absolutely don’t know what the Fisher-Yates shuffle algorithm is. Let’s tell ChatGPT to use the built-in sorting.
ChatGPT once again changes the implementation and uses the Array.Sort method instead of the previous algorithm. Again, it also explains in depth how the implementation works.
I quickly tested the code in Visual Studio, and it works as expected.
There is nothing that I would change in this code, so let’s move on to the third and last example, which is completely different than the two we already had.
Experiment 3: General Programming Questions
What is the difference between React and Blazor?
With this query, I want to see how ChatGPT can give us advice for software development beyond code generation.
ChatGPT responds with a great overview and comparison of both technologies.
However, I wonder what technology ChatGPT would suggest using for a C# developer with 5 years for a project with about 200 users and an application of about 10 pages with authentication.
It now suggests using ASP.NET Core with Razor Pages or MVC. It also explains the decision in detail. In the end, it even tells us that both Razor Pages and MVC are good choices because we already have experience with C# development.
Remember, we started with a query comparing React and Blazor. Let’s ask ChatGPT why it recommends Razor Pages and MVC but not Blazor.
It provides us with great detail on why it thinks that Blazor isn’t the right choice for the project and why ASP.NET Core with Razor Pages or MVC might be the better option.
I’m impressed with how detailed the explanations are and how much it takes my input into consideration, such as how much experience you have with what technology.
However, I would never let ChatGPT make architectural or technological decisions for a software project. But it is definitely a great starting point to get an opinion about a choice.
It’s like asking a co-worker for advice. You learn something from speaking with your co-worker, but you will want to make sure the information provided is correct anyway.
Conclusion
So, what do I think about ChatGPT? I have used it a few times through the last weeks, and I am definitely impressed by its level of detail. It’s a great starting point to let ChatGPT generate code if you already know what you need.
You can also ask architectural or technological questions. It’s like googling but more personal and tailored to your situation.
Of course, we still need to fact-check the answers, improve and test the code, and generally use our brains when working with ChatGPT.
For me, it is a helpful tool but nowhere near replacing developers. You have to be a developer to feed the right queries and to understand the output. However, I do believe it can hugely improve productivity in certain situations.
What is your experience with ChatGPT, and would you use it for .NET development? If you have already tried it, what were your results? Is there something you want me to try? If you happen to subscribe to my YouTube channel, I’ll see you in the next video.