Skip to main content

Appendix F - C# Prompt Engineering Guide (Revised)

A comprehensive guide to leveraging AI tools for C# development across all skill levels


Quick Reference Cheat Sheet

For immediate use, follow this structure.

Anatomy of a Perfect Prompt

A perfect prompt provides Role, Context, Intent, Constraints, and a specified Format (R-CIC-F).

  1. Role: "Act as a..." (e.g., senior C# developer, security expert).
  2. Context: "I'm using..." (e.g., .NET 8, ASP.NET Core). Provide relevant code snippets.
  3. Intent: "Write a method that..." or "Refactor this code to..."
  4. Constraints: "It must..." (e.g., target .NET 8, not use external libraries, follow SOLID).
  5. Format: "Provide..." (e.g., only the C# code, include XML comments, explain trade-offs).

Super-Template Example

Act as a [Role]. I am working on a [Context: Application Type] using [Context: Frameworks/Libraries].

Here is my existing code:
[Context: Code Snippet]

My goal is to [Intent: e.g., add a feature, fix a bug, refactor]. Please write the code to [Intent: Specific Action].

It must adhere to the following constraints:
- [Constraint 1]
- [Constraint 2]

Please provide the output in the following format:
- [Format: e.g., C# code only, with XML comments]

Introduction

Artificial Intelligence tools like ChatGPT, GitHub Copilot, and Microsoft Copilot have revolutionized how developers write, debug, and learn code. This guide will help you master the art of prompt engineering specifically for C# development, enabling you to transform your development process.

This guide will teach you to:

  • Generate high-quality, production-ready C# code through well-crafted prompts.
  • Debug complex issues with targeted AI assistance.
  • Accelerate your learning journey with AI-guided explanations and practice.
  • Improve productivity across all major C# frameworks, from web to desktop to game development.

Whether you're a beginner taking your first steps in C# or an experienced developer seeking to enhance your workflow, this guide provides the practical techniques needed to leverage AI as a powerful partner in your development process.

The Iterative Mindset

The single most important skill for effective prompt engineering is to treat your interaction with the AI as a conversation, not a command. Don't expect the perfect result on the first try.

Think of the AI as a junior developer who is brilliant and fast but lacks context. Your job is to provide that context through a series of refinements.

  1. Start with a simple prompt. Get a baseline result.
  2. Provide feedback and add context. "That's a good start, but you forgot to handle null inputs."
  3. Add constraints. "Now, refactor that code to improve performance for large datasets."
  4. Ask for alternatives. "Can you show me how to do this using a more functional approach with LINQ?"

Example of an Iterative Conversation:

  • You (V1): "Write a C# method that reads a CSV file."
  • AI (V1): Provides a basic method using File.ReadAllLines and string.Split.
  • You (V2): "Good. Now modify it to handle files with a header row and return a List<Dictionary<string, string>>."
  • AI (V2): Refactors the code to parse the header and create a list of dictionaries.
  • You (V3): "This is better, but it will consume too much memory on large files. Please refactor it to use yield return so it can process the file line-by-line without loading it all into memory."
  • AI (V3): Provides a final, memory-efficient implementation using an IEnumerable and yield return.

Embrace this back-and-forth process. Iteration is the key to unlocking complex and high-quality results.


Fundamentals of AI-Assisted C# Development

Understanding AI Code Assistants

AI code assistants are large language models trained on vast repositories of code, text, and documentation. They can:

  • Generate code snippets, complete functions, or even entire classes.
  • Explain complex code behavior and programming concepts.
  • Suggest optimizations, refactorings, and best practices.
  • Help identify and fix bugs by analyzing code and error messages.

Key AI Tools for C# Development

  1. ChatGPT (OpenAI)

    • Best for: Conversational problem-solving, debugging, brainstorming, and generating complete solutions from scratch.
  2. GitHub Copilot

    • Best for: Real-time, in-IDE code completion and suggestions. It excels at understanding the context of your current file and project.
  3. Microsoft Copilot

    • Best for: Developers deeply integrated into the Microsoft ecosystem (Visual Studio, .NET). Offers enhanced, context-aware chat and analysis capabilities for .NET.
  4. Other Tools

    • Tabnine: A privacy-focused AI assistant that can run locally.
    • Amazon CodeWhisperer: An excellent choice for developers working within the AWS ecosystem.

Crafting Effective Prompts for C# Code Generation

The Anatomy of a Perfect Prompt

An effective C# prompt provides clear and comprehensive instructions. The best prompts include all five elements from the Cheat Sheet: Role, Context, Intent, Constraints, and Format.

Basic Prompt Templates

Function Implementation

Act as a senior C# developer. Write a C# method that [specific functionality].

The method should:
- Accept parameters: [parameter types and descriptions]
- Return: [return type and description]
- Handle these edge cases: [list edge cases]
- Follow these constraints: [e.g., use regular expressions, target .NET 8]
- Include XML documentation comments.

Class Design

Act as a software architect. Design a C# class for a [purpose].

The class should:
- Be named [ClassName].
- Include these properties: [list properties with types and purposes].
- Include these methods: [list methods with signatures and purposes].
- Implement these interfaces: [list interfaces].
- Follow these design patterns: [relevant patterns like Singleton, Factory, etc.].
- Be designed for dependency injection.

Intermediate Prompt Techniques

Specifying Code Style and Standards

Generate C# code following Microsoft's official coding conventions for C# 12:
- Use PascalCase for public members and types.
- Use camelCase for local variables and private fields, prefixing private fields with an underscore (_).
- Use expression-bodied members where appropriate.
- Use file-scoped namespaces.
- Include XML documentation for all public APIs.

Requesting Multiple Implementations

Provide three different C# implementations of a method that [functionality], and explain the trade-offs for each:

1. A simple, readable version using a straightforward algorithm.
2. A performance-optimized version (e.g., using less memory allocation).
3. A version that prioritizes functional programming principles (e.g., using LINQ and immutable types).

Advanced Prompt Engineering

Context-Rich Prompts

This is the key to solving complex problems. Provide as much relevant information as possible.

I'm working on an ASP.NET Core 8 Web API using Entity Framework Core and a SQL Server database. Here is my 'Product' entity and my 'DbContext':

[Paste Product.cs and ApplicationDbContext.cs code]

I need to add a new method to my 'ProductRepository' class that implements pagination. Here is the current repository:

[Paste ProductRepository.cs code]

Please provide an implementation for 'GetProductsPagedAsync(int pageNumber, int pageSize)' that:
- Is highly performant and avoids loading the entire table into memory.
- Returns a 'PagedResult<Product>' object containing the list of products for the page, and metadata like TotalCount and TotalPages.
- Includes filtering and sorting capabilities.
- Adheres to modern async/await best practices.

Prompt Anti-Patterns: What to Avoid

To get the best results, avoid these common mistakes:

  • Vague Requests:

    • Bad: "Make a product manager."
    • Good: "Write a C# console application to manage products. It should allow adding, deleting, and viewing products stored in a local JSON file. A product has an ID, Name, and Price."
  • Pasting Code Without Context:

    • Bad: "Fix this." [Pastes 50 lines of code]
    • Good: "I'm trying to implement a search feature in my WPF app. The code below is supposed to filter a list based on user input, but it's not updating the UI. Here's my ViewModel and the method. What am I missing in my MVVM implementation?"
  • Asking for Too Much at Once:

    • Bad: "Build me a complete e-commerce application."
    • Good: Start small. "Design the EF Core entities for a simple e-commerce system with Products, Orders, and Customers."
  • Ignoring AI Limitations:

    • Bad: "Write me C# code using the new features in .NET 10." (When the AI's knowledge only goes up to .NET 8).
    • Good: "How would I solve this problem using features available in .NET 8? What upcoming features in .NET 9 might change this approach?"

Framework-Specific Prompt Engineering

ASP.NET Core

Act as an ASP.NET Core expert. Generate a C# Web API controller for a 'Book' resource that:
- Uses ASP.NET Core 8.
- Implements full CRUD operations (GET, GET by ID, POST, PUT, DELETE).
- Follows RESTful conventions with proper HTTP verbs and status codes (200, 201, 204, 400, 404).
- Uses dependency injection to get an 'IBookRepository' service.
- Implements JWT-based authorization, requiring an 'Admin' role for write operations.
- Includes detailed Swagger/OpenAPI documentation comments.

Entity Framework Core

Act as a database specialist using EF Core. Optimize this LINQ query for performance:

[Paste slow LINQ query]

The query is slow when the 'Orders' table has millions of records. Please provide a revised version and explain your optimizations. Consider:
- Avoiding the N+1 problem with eager loading (`Include`/`ThenInclude`).
- Projecting directly to a DTO using `Select` to reduce data transfer.
- Using `AsNoTracking()` for read-only queries.
- Implementing efficient pagination.
- Suggesting necessary database indexes.

WPF and Desktop Applications

Act as a WPF expert. I need to create a view and viewmodel for a customer details page using the MVVM pattern.

Please provide the C# code for:
1. A 'CustomerViewModel' that implements `INotifyPropertyChanged`. It should have properties for FirstName, LastName, and a 'Save' command.
2. A modern `RelayCommand` implementation for the `ICommand` interface.
3. The XAML for the 'CustomerView' that binds to the viewmodel properties and command.
4. An explanation of how the data binding connects the View and ViewModel.

.NET MAUI & Blazor

Act as a .NET MAUI developer. I need to implement a feature that accesses the device's geolocation.

Provide a C# service class (`GeolocationService`) that:
- Follows the MVVM pattern and is suitable for dependency injection.
- Correctly handles platform-specific permissions for iOS and Android.
- Provides a method `GetCurrentLocationAsync` that returns the current location or handles cases where permission is denied.
- Shows how to inject and call this service from a Blazor component.

Unity Game Development

Act as a senior Unity developer. Write a C# script for a player health system.

The script should:
- Be named 'PlayerHealth'.
- Have a public integer property for 'MaxHealth' and a private one for 'CurrentHealth'.
- Include a public method 'TakeDamage(int amount)' that reduces health and checks for player death.
- Include a public method 'Heal(int amount)' that restores health but doesn't exceed MaxHealth.
- When the player's health drops to zero, it should log a message to the console and disable the player's 'PlayerController' script.
- Include comments explaining the key parts of the code.

Advanced Techniques

AI-Assisted Code Review and Refactoring

Act as a principal software engineer conducting a code review. Analyze this C# service class and provide feedback.

[Paste C# class code]

Focus your review on:
- **SOLID Principles**: Does the class have a single responsibility? Are dependencies handled correctly?
- **Security**: Are there any vulnerabilities (e.g., SQL injection, improper handling of sensitive data)?
- **Performance**: Are there any performance bottlenecks or inefficient patterns?
- **Readability & Maintainability**: Is the code clean, well-documented, and easy to understand?
- **Error Handling**: Is exception handling robust and consistent?

For each point, explain the issue and provide a corrected code snippet.

Building a Prompt Library

For teams, a shared repository of well-crafted prompts can dramatically improve consistency and efficiency.

  1. Use a Shared Repository: Use a tool like a Git repository with Markdown files, a team Wiki, or Notion.
  2. Categorize Prompts: Organize prompts by task (e.g., "EFCore-Queries," "Unit-Test-Generation," "API-Controller-Setup").
  3. Create Templates: For each category, create a template with clear placeholders. Use a simple, repeatable format.

Example Prompt: The below prompt generates a standard repository method with filtering and sorting.

Act as a C# and EF Core expert. I am using .NET 8.

Here is my entity:
// Paste Entity Code Here

Here is my DbContext:
// Paste DbContext Code Here

Please write a repository method named `[YourMethodName]` that [describe functionality].

It must:
- Be asynchronous.
- Use `AsNoTracking()` for performance.
- [Add other constraints].

Provide only the C# method as a response.
  1. Version and Refine: Encourage the team to add new "winning" prompts and refine existing ones that produce excellent results.

Your Professional Responsibilities

Code Quality and Verification

Always treat AI-generated code as a first draft. You are the developer of record.

  • Verify Correctness: Write unit tests to confirm the code behaves as expected.
  • Check for Security: Manually inspect for vulnerabilities. Do not assume the code is secure.
  • Beware of Hallucinations: AI can invent plausible-looking but non-existent methods, properties, or even entire libraries. Always verify its output against official documentation.
  • Ensure It Fits Your Style: Refactor the code to match your project's existing architecture and coding standards.

Ethical and Professional Considerations

  • Data Privacy & IP: NEVER paste sensitive, confidential, or proprietary code into public AI tools. Use enterprise-grade tools like GitHub Copilot for Business that are designed with privacy and IP protection in mind.
  • Code Licensing & Ownership: Be aware of the licensing implications of generated code. The AI may have been trained on open-source code with various licenses. Use tools that can filter suggestions matching public code.
  • Accountability: You are ultimately accountable for the code you commit, regardless of its origin. You cannot blame the AI for a bug that makes it to production.
  • Intellectual Atrophy (Over-reliance): Relying too heavily on AI can weaken your fundamental problem-solving skills. Use AI as a tool to augment your abilities, not replace them. Always take the time to understand the code the AI generates. If you don't understand it, ask the AI to explain it until you do.

Resources and Tools

  • Recommended IDEs:
    • Microsoft Visual Studio: The premier IDE for .NET development.
    • JetBrains Rider: A fast, cross-platform .NET IDE.
    • Visual Studio Code: A lightweight editor with the powerful C# Dev Kit extension.
  • Essential Extensions and Tools:
    • GitHub Copilot / Microsoft Copilot: For real-time AI assistance.
    • ReSharper/Rider: For advanced code analysis and refactoring.
    • SonarLint: For on-the-fly code quality and security feedback.
    • BenchmarkDotNet: For reliable performance testing.

Conclusion

Mastering prompt engineering is a new, essential skill for the modern C# developer. It is a force multiplier that allows you to offload cognitive work, accelerate development, and focus on solving higher-level problems. By providing clear, context-rich, and specific prompts within an iterative conversation, you can transform AI from a simple code completion tool into a true development partner.

This field is evolving rapidly. The key to long-term success is to remain curious, practice deliberately, and continuously refine your approach. Use this guide as a foundation, build your own prompt library, and embrace the collaborative future of software development.