Smarter Code with Built-in AI Support in C# 14

Overview

With C# 14, AI-assisted features streamline software development, allowing code generation, refactoring, and debugging to be more efficient. Visual Studio and .NET tooling come with built-in AI capabilities that enable developers to write clean, maintainable code with machine learning-powered suggestions, autocompletions, and intelligent debugging.

With practical examples, we will explore how to leverage AI in C# 14 to enhance your development workflow.

Generate code with AI-Assistance

AI-assisted code generation is one of the most exciting features of C# 14, powered by deep learning models integrated into the Visual Studio IDE, which suggests relevant code snippets based on your project context.

Visual Studio AI-Generated Methods

With AI assistance, Visual Studio can automatically generate the method based on your comments and method signature when you're working on a method to fetch data from a database.

namespace AISmartCodeWithCSharp14.Models;

public record User
{
    public Guid Id { get; init; }
    public string FirstName { get; init; } = string.Empty;
    public string LastName { get; init; } = string.Empty;
    public string EmailAddress { get; init; } = string.Empty;
    public DateTime DateOfBirth { get; init; }
    public string TelephoneNumber { get; init; }=string.Empty;
    public DateTime CreatedAt { get; init; }

    public string FullName => $"{FirstName} {LastName}";
    public string FullDetials => $"{FullName} ({DateOfBirth}) ({EmailAddress}) ({TelephoneNumber})";
}
using AISmartCodeWithCSharp14.Models;
using Microsoft.EntityFrameworkCore;

namespace AISmartCodeWithCSharp14.Services;

public class UserService
{
    private readonly DbContext _context;

    public UserService(DbContext context)
    {
        _context = context;
    }

    // AI-assisted method generation
    /// <summary>
    /// Retrieves a user by their ID.
    /// </summary>
    public async Task<User?> GetUserByIdAsync(Guid id) =>
    await _context.Set<User>().FirstOrDefaultAsync(u => u.Id == id);
}

How It Works

  • Using comments and signatures, artificial intelligence can determine the intent of a method.
  • Based on project structure and best practices, suggests an optimal implementation.
  • Enhances efficiency by reducing the need for manual coding.

Coding Refactoring Powered by  AI

AI in C# 14 automatically detects potential improvements and suggests smart refactoring’s for maintaining clean, efficient, and scalable code.

Code To Refactoring Suggested by AI

Here is an example of a redundant logic method that AI can optimize:

Before Refactoring

/*Before AI Refactoring Code*/
public void LogMessage(string message)
{
    if (!string.IsNullOrEmpty(message))
    {
        Console.WriteLine(message);
    }
}

AI-Suggested Refactoring (C# 14)

  /*After AI Refactoring Code*/
  public void LogMessage(string message)=>
      Console.WriteLine(message ?? "Default log message"); 

Benefits of AI-Powered Refactoring

  • Eliminates redundant conditions and simplifies expressions.
  • Provides optimal LINQ queries, method chaining, and pattern-matching suggestions.
  • Improves code readability by preventing common anti-patterns.

Using AI to Debug and Resolve Errors

Using artificial intelligence-powered debugging tools, C# 14 analyzes runtime behavior, detects anomalies, and suggests fixes instantly. Also, the AI-powered tools can learn from past errors, further enhancing their diagnostic capabilities over time. This allows developers to identify and resolve issues more efficiently.

Debugging with AI in Action

A list becomes null unexpectedly because of a bug. AI can detect this and provide suggestions. It can identify if the list was not properly initialized or if it was not receiving the right data. AI can also recommend adding null checks or initializing the list correctly to prevent this bug from occurring in the future.

Before Debugging

 //AI-Debugging method
public void PrintUserNames(List<User> users)
{
    foreach (var user in users)
    {
        Console.WriteLine(user.Name);
    }
}

The NullReferenceException will be thrown if a user is null. AI will suggest a fixing solution if a user is null.

AI-Suggested Fix

//AI-Debugging Suggested Fix
public void PrintUserNames(List<User>? users)
{
    if (users is not { Count: > 0 })
    {
        Console.WriteLine("No users found.");
        return;
    }

    users.ForEach(user => Console.WriteLine(user.FullName));
} 

AI Debugging Features in C# 14

  • Artificial Intelligence (AI) suggests the best fixes for runtime errors.
  • A predictive debugging approach detects potential problems before they occur.
  • Highlights potential null values, type mismatches, and performance bottlenecks in the code.

Optimizing Performance with AI

 With AI in C# 14, you can analyze code and provide performance enhancements.

  • LINQ queries have been optimized.
  • Improved responsiveness with asynchronous patterns.
  • Preventing memory leaks with memory management techniques.

Using AI to Optimized LINQ Query

Before Optimization

namespace AISmartCodeWithCSharp14.Models;
public record Product(int Id, string Name, decimal Price);

 using AISmartCodeWithCSharp14.Models;

namespace AISmartCodeWithCSharp14.Services;

public class ProductService
{
    private readonly List<Product> _products = new()
    {
        new(1, "Laptop", 1200),
        new(2, "Keyboard", 50),
        new(3, "Monitor", 300),
        new(4, "Mouse", 30),
        new(5, "Tablet", 200)
    };
    /// Not AI-Optimized Query
    public List<Product> GetExpensiveProducts()
    {
        return _products.Where(p => p.Price > 100)
                        .OrderBy(p => p.Name)
                        .ToList(); // Eager execution
    }
}

AI-Optimized Query

using AISmartCodeWithCSharp14.Models;

namespace AISmartCodeWithCSharp14.Services;

public class ProductService
{
    private readonly List<Product> _products = new()
    {
        new(1, "Laptop", 1200),
        new(2, "Keyboard", 50),
        new(3, "Monitor", 300),
        new(4, "Mouse", 30),
        new(5, "Tablet", 200)
    };
      // AI-Optimized Query
    public IEnumerable<Product> GetExpensiveProducts()
    {
        return _products.Where(p => p.Price > 100)
                        .OrderBy(p => p.Name)
                        .AsEnumerable(); // Optimized for in-memory processing
    }
}

AI Suggestions

  • This method prevents unnecessary database queries in Entity Framework by using AsEnumerable().
  • Better performance is achieved by optimizing the order of execution.

Using AI to Assist Test Generation

Writing unit tests is time-consuming. AI in C# 14 can generate meaningful test cases automatically, saving developers valuable time and allowing them to work on more complex projects. Through the automation of test case generation, AI ensures thorough coverage and improves code quality.

AI-Generated Unit Test

Production Code

namespace AISmartCodeWithCSharp14.Utilities;
public class Calculator
{
    public int Add(int a, int b) => a + b;

    public int Subtract(int a, int b) => a - b;

    public int Multiply(int a, int b) => a * b;

    public double Divide(int a, int b)
    {
        if (b == 0)
        {
            throw new DivideByZeroException("Cannot divide by zero.");
        }
        return (double)a / b;
    }
} 

AI-Generated Unit Test

 using AISmartCodeWithCSharp14.Utilities;

namespace AISmartCodeWithCSharp14Tests;

public class CalculatorTests
{
    private readonly Calculator _calculator;

    public CalculatorTests()
    {
        _calculator = new Calculator();
    }

    [Fact] 
    public void Add_ShouldReturnCorrectSum()
    {
        int result = _calculator.Add(2, 3);
        Assert.Equal(5, result);
    }

    [Fact]
    public void Subtract_ShouldReturnCorrectDifference()
    {
        int result = _calculator.Subtract(10, 5);
        Assert.Equal(5, result);
    }

    [Fact]
    public void Multiply_ShouldReturnCorrectProduct()
    {
        int result = _calculator.Multiply(4, 5);
        Assert.Equal(20, result);
    }

    [Fact]
    public void Divide_ShouldReturnCorrectQuotient()
    {
        double result = _calculator.Divide(10, 2);
        Assert.Equal(5, result);
    }

    [Fact]
    public void Divide_ByZero_ShouldThrowException()
    {
        var exception = Assert.Throws<DivideByZeroException>(() => _calculator.Divide(10, 0));
        Assert.Equal("Attempted to divide by zero.", exception.Message);
    }
}

Advantages of AI-Powered Test Generation

  • Tests are automatically generated based on logic in methods.
  • Covers all tests thoroughly.
  • Provides edge case detection and boundary condition detection.

Summary

With C# 14, AI-assisted development transforms how code is written, refactored, debugged, and optimized. Developers can develop more efficient and error-free applications using intelligent code suggestions, automated refactoring, AI-driven debugging, performance optimizations, and test generation.

Suppose AI-powered features are incorporated into your workflow. In that case, you will be able to write smarter, cleaner, and more maintainable code, which speeds up development while also ensuring a higher level of quality and reliability. By leveraging AI, developers can focus more on creative problem-solving and innovation, while AI-assisted tools handle routine tasks efficiently.

As C# 14 incorporates AI, efficiency will be boosted as well as modern software development will be redefined. As a result, developers will be able to write more efficient and effective code, resulting in faster development cycles and improved software performance. In addition, AI integration will enable developers to build and maintain software using new tools and insights.

I have uploaded the code example, which I have written for this article on my GitHub Repository https://github.com/ziggyrafiq/AISmartCodeWithCSharp14

Up Next
    Ebook Download
    View all
    Learn
    View all
    Capgemini is a global leader in consulting, technology services, and digital transformation.