Skip to content

fkucukkara/awesome-copilot-csharp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– Awesome GitHub Copilot - C# Development Edition

A specialized collection of GitHub Copilot customizations focused on C# and .NET development

Powered by Awesome Copilot License: MIT

This repository extends the official awesome-copilot repository with specialized C# and .NET development instructions, prompts, and chat modes.

🎯 What's Included

πŸ“‹ Custom Instructions

Enhance GitHub Copilot's behavior for C# development with specialized instruction sets:

🎯 Reusable Prompts

Ready-to-use prompt templates for specific C# development scenarios:

🧩 Custom Chat Modes

Specialized chat modes for different development workflows:

πŸš€ Quick Start Guide

πŸ“‹ Using Custom Instructions

GitHub Copilot Instructions automatically enhance Copilot's behavior for your entire workspace. Here's how to use them effectively:

Step-by-Step Setup

  1. Copy instruction files to your project's .github/ folder:

    your-project/
    └── .github/
        β”œβ”€β”€ copilot-instructions.md                    # Main C# guidelines
        └── instructions/
            β”œβ”€β”€ csharp-async-programming.instructions.md
            β”œβ”€β”€ csharp-testing.instructions.md
            └── entity-framework-core.instructions.md
    
  2. Instructions activate automatically when you open VS Code in that workspace

  3. No restart required - Copilot immediately uses the new guidelines

What Instructions Do

  • Code Generation: Copilot follows C# best practices when suggesting code
  • Code Completion: Suggestions align with your project's patterns
  • Chat Responses: Copilot Chat provides C#-specific guidance
  • Code Reviews: Copilot considers your guidelines when reviewing code

Example: Before vs After Instructions

Before (generic suggestion):

public async Task<string> GetData()
{
    var result = await httpClient.GetStringAsync(url);
    return result;
}

After (with async instructions):

public async Task<string> GetDataAsync(CancellationToken cancellationToken = default)
{
    var result = await httpClient.GetStringAsync(url, cancellationToken).ConfigureAwait(false);
    return result;
}

🎯 Using Reusable Prompts

Prompts are specialized commands you can run in GitHub Copilot Chat for specific tasks.

Installation & Usage

  1. Install a prompt by opening it in VS Code and clicking the install button
  2. Use in chat with /prompt-name syntax
  3. Target specific code by selecting text before running the prompt

Example: Async Code Review

1. Select your async method in the editor
2. Open Copilot Chat (Ctrl+Shift+I)
3. Type: /csharp-async-best-practices
4. Get detailed analysis and improvements

Sample Output:

βœ… Good Practices Found
- Proper async method naming with Async suffix
- Correct Task<T> return type

⚠️ Issues Identified
- Missing ConfigureAwait(false) on line 15
- CancellationToken not passed to inner calls

πŸ”§ Recommended Improvements
[Detailed code examples with fixes]

🧩 Using Chat Modes

Chat Modes are specialized AI personalities for different development scenarios.

Available Modes

πŸŽ“ C# Mentor Mode

  • Use when: Learning new concepts, code reviews, architecture decisions
  • Example conversation:
    You: "Should I use records or classes for my API DTOs?"
    
    Mentor: "For API DTOs, I recommend records because:
    1. Immutability prevents accidental modification
    2. Built-in equality comparison
    3. Concise syntax reduces boilerplate
    
    Here's an example:
    
    public record UserDto(int Id, string Name, string Email);
    
    This automatically provides proper equality, ToString(), and serialization behavior."
    

⚑ Beast Mode

  • Use when: High-performance coding, complex algorithms, optimization
  • Example conversation:
    You: "Optimize this LINQ query for large datasets"
    
    Beast: "Here's a high-performance approach using Span<T> and vectorization:
    [Provides optimized code with detailed performance analysis]"
    

How to Activate Chat Modes

  1. Install the chatmode file via VS Code Command Palette
  2. Switch modes in the Copilot Chat interface
  3. Context persists throughout your conversation

πŸ“ Repository Structure

.github/
β”œβ”€β”€ copilot-instructions.md          # Main C# development instructions
β”œβ”€β”€ instructions/                    # Specialized instruction sets
β”‚   β”œβ”€β”€ csharp-async-programming.instructions.md
β”‚   β”œβ”€β”€ csharp-testing.instructions.md
β”‚   └── entity-framework-core.instructions.md
β”œβ”€β”€ prompts/                        # Reusable prompt templates
β”‚   β”œβ”€β”€ csharp-async-best-practices.prompt.md
β”‚   β”œβ”€β”€ csharp-documentation-generator.prompt.md
β”‚   └── csharp-performance-analyzer.prompt.md
└── chatmodes/                      # Custom chat modes
    β”œβ”€β”€ csharp-mentor.chatmode.md
    β”œβ”€β”€ 4.1-Beast.chatmode.md
    └── Claude-CSharp-Beast.chatmode.md

πŸ› οΈ C# Development Features & Examples

πŸ”₯ Modern C# Support

C# 13 Features

Our instructions help Copilot suggest the latest C# features:

// Primary constructors with field keyword
public class UserService(IUserRepository repository) : IUserService
{
    private readonly field = repository ?? throw new ArgumentNullException(nameof(repository));
    
    public async Task<User> GetUserAsync(int id)
    {
        return await field.GetByIdAsync(id);
    }
}

// Collection expressions
List<string> names = ["Alice", "Bob", "Charlie"];
int[] numbers = [1, 2, 3, 4, 5];

Nullable Reference Types

Instructions ensure proper null handling:

// βœ… Copilot suggests proper null checks
public string FormatUserName(User? user)
{
    return user is not null 
        ? $"{user.FirstName} {user.LastName}"
        : "Unknown User";
}

// βœ… Copilot avoids unnecessary null checks when type system guarantees non-null
public void ProcessValidUser(User user) // Never null based on context
{
    Console.WriteLine(user.Name); // No null check needed
}

🌐 .NET Ecosystem Integration

ASP.NET Core Web API

Generate modern API controllers with proper patterns:

[ApiController]
[Route("api/[controller]")]
public class UsersController(IUserService userService) : ControllerBase
{
    [HttpGet("{id:int}")]
    [ProducesResponseType<UserDto>(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<UserDto>> GetUserAsync(
        int id, 
        CancellationToken cancellationToken = default)
    {
        var user = await userService.GetUserAsync(id, cancellationToken);
        return user is not null 
            ? Ok(user.ToDto()) 
            : NotFound();
    }
}

Entity Framework Core

Get optimized data access patterns:

public class UserRepository(AppDbContext context) : IUserRepository
{
    public async Task<User?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        return await context.Users
            .Include(u => u.Profile)
            .FirstOrDefaultAsync(u => u.Id == id, cancellationToken);
    }
    
    public async Task<IReadOnlyList<User>> GetActiveUsersAsync(CancellationToken cancellationToken = default)
    {
        return await context.Users
            .Where(u => u.IsActive)
            .AsNoTracking() // Performance optimization for read-only queries
            .ToListAsync(cancellationToken);
    }
}

πŸ§ͺ Testing Excellence

Unit Testing with Best Practices

Instructions guide proper test structure:

public class UserServiceTests
{
    private readonly Mock<IUserRepository> _mockRepository;
    private readonly UserService _userService;

    public UserServiceTests()
    {
        _mockRepository = new Mock<IUserRepository>();
        _userService = new UserService(_mockRepository.Object);
    }

    [Fact]
    public async Task GetUserAsync_WithValidId_ReturnsUser()
    {
        // Arrange
        var userId = 1;
        var expectedUser = new User { Id = userId, Name = "John Doe" };
        _mockRepository.Setup(r => r.GetByIdAsync(userId, default))
                      .ReturnsAsync(expectedUser);

        // Act
        var result = await _userService.GetUserAsync(userId);

        // Assert
        result.Should().NotBeNull();
        result.Id.Should().Be(userId);
        result.Name.Should().Be("John Doe");
    }

    [Fact]
    public async Task GetUserAsync_WithInvalidId_ReturnsNull()
    {
        // Arrange
        _mockRepository.Setup(r => r.GetByIdAsync(999, default))
                      .ReturnsAsync((User?)null);

        // Act
        var result = await _userService.GetUserAsync(999);

        // Assert
        result.Should().BeNull();
    }
}

Integration Testing

Get complete API testing setups:

public class UsersControllerIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;
    private readonly HttpClient _client;

    public UsersControllerIntegrationTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
        _client = _factory.CreateClient();
    }

    [Fact]
    public async Task GetUser_ReturnsSuccessAndCorrectContentType()
    {
        // Act
        var response = await _client.GetAsync("/api/users/1");

        // Assert
        response.EnsureSuccessStatusCode();
        response.Content.Headers.ContentType?.ToString()
            .Should().Be("application/json; charset=utf-8");
    }
}

πŸ—οΈ Architecture Patterns

Clean Architecture Structure

Instructions help organize code properly:

src/
β”œβ”€β”€ YourApp.Domain/              # Business logic & entities
β”‚   β”œβ”€β”€ Entities/
β”‚   β”œβ”€β”€ Interfaces/
β”‚   └── ValueObjects/
β”œβ”€β”€ YourApp.Application/         # Use cases & services
β”‚   β”œβ”€β”€ Services/
β”‚   β”œβ”€β”€ DTOs/
β”‚   └── Interfaces/
β”œβ”€β”€ YourApp.Infrastructure/      # Data access & external services
β”‚   β”œβ”€β”€ Data/
β”‚   β”œβ”€β”€ Repositories/
β”‚   └── Services/
└── YourApp.Web/                # API controllers & startup
    β”œβ”€β”€ Controllers/
    β”œβ”€β”€ Middleware/
    └── Program.cs

Dependency Injection Setup

Get proper DI configuration:

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Domain services
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IUserRepository, UserRepository>();

// Infrastructure
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Add health checks
builder.Services.AddHealthChecks()
    .AddDbContextCheck<AppDbContext>();

var app = builder.Build();

// Configure middleware pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHealthChecks("/health");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

πŸ’‘ Real-World Usage Scenarios

Scenario 1: Code Review Assistant

  1. Select problematic code in your editor
  2. Run: /csharp-async-best-practices in Copilot Chat
  3. Get: Detailed analysis with specific improvements
  4. Apply: Suggested changes with explanations

Scenario 2: Learning New Patterns

  1. Switch to: C# Mentor chat mode
  2. Ask: "How do I implement the Repository pattern with EF Core?"
  3. Get: Complete example with explanations and best practices
  4. Follow up: With specific questions about implementation details

Scenario 3: Performance Optimization

  1. Switch to: Beast Mode chat mode
  2. Share: Your performance-critical code
  3. Get: Optimized version with benchmarks and explanations
  4. Learn: Advanced techniques like Span<T>, vectorization, memory management

Scenario 4: Documentation Generation

  1. Select: Your public API methods
  2. Run: /csharp-documentation-generator
  3. Get: Complete XML documentation with examples
  4. Customize: Based on your project's documentation standards

🀝 Contributing

We welcome contributions! Here's how you can help improve this collection.

🎯 What Can You Contribute?

πŸ“‹ New Instructions

Add specialized guidelines for specific C# scenarios:

Example: API Security Instructions

---
description: 'Security best practices for ASP.NET Core APIs'
applyTo: '**/Controllers/*.cs'
---

# API Security Guidelines

## Authentication & Authorization
- Always validate JWT tokens properly
- Use [Authorize] attributes on controllers
- Implement role-based access control (RBAC)
[... detailed guidelines ...]

🎯 New Prompts

Create automation prompts for common development tasks:

Example: Database Migration Prompt

---
name: ef-migration-generator
description: Generate Entity Framework Core migrations with proper naming
---

# EF Core Migration Generator

Analyze the current DbContext changes and generate:
1. Descriptive migration name
2. Migration command
3. Rollback instructions
4. Testing recommendations

🧩 New Chat Modes

Design specialized AI assistants:

Example: Performance Analyzer Mode

---
name: csharp-performance-analyzer
description: Specialized in C# performance optimization
model: gpt-4o
---

You are a C# performance expert focused on:
- Memory allocation analysis
- Garbage collection optimization  
- Algorithm complexity assessment
- Benchmarking recommendations

πŸ“ Contribution Process

1. Fork & Clone

git clone https://github.com/your-username/awesomeCopilot.git
git clone https://github.com/fkucukkara/awesome-copilot-csharp.git
cd awesomeCopilotCSHARP

2. Create Feature Branch

git checkout -b feature/new-performance-instructions

3. Add Your Contribution

Place files in the appropriate directory:

  • Instructions: .github/instructions/
  • Prompts: .github/prompts/
  • Chat Modes: .github/chatmodes/

4. Test Your Contribution

  • Test instructions: Create a sample C# project and verify Copilot behavior
  • Test prompts: Install and run in VS Code, check output quality
  • Test chat modes: Engage in conversations, verify responses

5. Update Documentation

Add your contribution to:

  • README.md (this file)
  • Any relevant section documentation

6. Submit Pull Request

Include in your PR:

  • Clear description of what you've added
  • Testing evidence (screenshots, examples)
  • Use cases where your contribution helps

πŸ§ͺ Testing Guidelines

For Instructions

  1. Create a new C# project
  2. Copy your instruction file to .github/
  3. Write sample code and verify Copilot suggestions follow your guidelines
  4. Test both code completion and chat responses

For Prompts

  1. Install your prompt in VS Code
  2. Test with various code examples
  3. Verify output matches expected format
  4. Check error handling with invalid inputs

For Chat Modes

  1. Install and activate the chat mode
  2. Have conversations covering different scenarios
  3. Verify the AI maintains the intended personality
  4. Test knowledge boundaries and accuracy

πŸ”§ Troubleshooting & FAQ

Common Issues

"Instructions aren't working"

Symptoms: Copilot suggestions don't follow your custom guidelines

Solutions:

  1. Check file location: Instructions must be in .github/ folder
  2. Verify file extension: Must end with .instructions.md
  3. Restart VS Code: Sometimes needed for new instructions
  4. Check syntax: YAML frontmatter must be valid

Example fix:

---
description: 'Your description here'  # Quotes required
applyTo: '**/*.cs'                    # Proper glob pattern
---

"Prompts not appearing in chat"

Symptoms: Can't use /your-prompt-name in Copilot Chat

Solutions:

  1. Install properly: Use VS Code's install button on the prompt file
  2. Check naming: Prompt name in YAML must match filename
  3. Restart chat: Close and reopen Copilot Chat
  4. Verify VS Code version: Needs recent VS Code with Copilot Chat

"Chat mode not working"

Symptoms: Chat mode doesn't activate or behaves incorrectly

Solutions:

  1. Check model availability: Ensure specified model is accessible
  2. Verify tools: Some chat modes require specific VS Code extensions
  3. Reset chat: Start a new conversation
  4. Check syntax: YAML frontmatter must be valid

Performance Tips

Optimize Instruction Files

  • Be specific: Target exact file patterns with applyTo
  • Keep focused: One instruction file per domain (async, testing, etc.)
  • Use examples: Include code examples in instructions

Effective Prompt Design

  • Clear objectives: State exactly what the prompt should do
  • Expected format: Define output structure
  • Error handling: Include guidance for edge cases

Chat Mode Best Practices

  • Consistent personality: Maintain the same tone throughout
  • Domain expertise: Focus on specific areas of knowledge
  • Helpful responses: Always provide actionable advice

Getting Help

πŸ› Found a Bug?

  1. Check existing issues in the repository
  2. Create detailed issue with reproduction steps
  3. Include environment info (VS Code version, Copilot version)

οΏ½ Have Questions?

  1. Check documentation in this README
  2. Look at examples in existing files
  3. Ask in discussions for help with contributions

πŸš€ Want to Collaborate?

  1. Join discussions about new features
  2. Propose improvements to existing content
  3. Share your use cases to help others

πŸ“š Additional Resources & Quick Reference

πŸ”— Essential Links

⚑ Quick Reference

File Organization

.github/
β”œβ”€β”€ copilot-instructions.md          # 🎯 Main C# guidelines (always include)
β”œβ”€β”€ instructions/                    # πŸ“‹ Specialized rules
β”‚   β”œβ”€β”€ csharp-async-programming.instructions.md     # Async/await patterns
β”‚   β”œβ”€β”€ csharp-testing.instructions.md               # Testing best practices  
β”‚   └── entity-framework-core.instructions.md       # EF Core optimization
β”œβ”€β”€ prompts/                        # 🎯 Automation commands
β”‚   β”œβ”€β”€ csharp-async-best-practices.prompt.md       # Async code analysis
β”‚   β”œβ”€β”€ csharp-documentation-generator.prompt.md    # XML doc generation
β”‚   └── csharp-performance-analyzer.prompt.md       # Performance analysis
└── chatmodes/                      # 🧩 AI assistants
    β”œβ”€β”€ csharp-mentor.chatmode.md                   # Learning & guidance
    β”œβ”€β”€ 4.1-Beast.chatmode.md                       # High-performance coding
    └── Claude-CSharp-Beast.chatmode.md             # Advanced C# expert

Chat Commands Quick Reference

Command Purpose Best Used For
/csharp-async-best-practices Analyze async code patterns Code reviews, performance optimization
/csharp-documentation-generator Generate XML documentation API documentation, code completion
/csharp-performance-analyzer Memory allocation and performance analysis Performance optimization, bottleneck identification

Chat Mode Switching

Mode Personality Use Cases
C# Mentor πŸŽ“ Patient teacher Learning, explanations, best practices
Beast Mode ⚑ Performance expert Optimization, algorithms, advanced patterns
Claude C# Beast πŸš€ Advanced expert Complex architecture, design patterns

Instruction File Patterns

Pattern Target Files Purpose
**/*.cs All C# files General C# guidelines
**/*Test.cs Test files only Testing-specific rules
**/*DbContext.cs EF DbContext files Database-specific patterns
**/Controllers/*.cs API controllers Web API best practices

🎯 When to Use What

Starting a New Project

  1. Copy: copilot-instructions.md to your .github/ folder
  2. Add: Relevant specialized instructions based on your tech stack
  3. Install: Useful prompts for your development workflow

Code Review Process

  1. Select: Code to review in VS Code
  2. Run: Appropriate analysis prompt (e.g., /csharp-async-best-practices)
  3. Apply: Suggested improvements
  4. Document: Changes with generated documentation

Learning & Development

  1. Switch to: C# Mentor chat mode
  2. Ask: Specific questions about patterns, frameworks, or best practices
  3. Request: Examples and explanations
  4. Practice: Implementing suggested patterns

Performance Optimization

  1. Switch to: Beast Mode chat mode
  2. Share: Performance-critical code
  3. Get: Optimized implementations with benchmarks
  4. Test: Performance improvements in your application

πŸ”§ Customization Tips

Creating Project-Specific Instructions

---
description: 'Your project-specific C# guidelines'
applyTo: 'src/**/*.cs'  # Target only your src folder
---

# Project-Specific Guidelines

## Domain Rules
- Use your business domain terminology
- Follow your specific naming conventions
- Include your architecture patterns

## Integration Requirements  
- Include your specific logging patterns
- Add your error handling approaches
- Document your testing strategies

Extending Existing Prompts

---
name: your-custom-prompt
description: Extended version of existing prompt
author: your-name
version: 1.0.0
extends: csharp-async-best-practices  # Reference base prompt
---

# Enhanced Async Analysis

Include all base functionality plus:
- Your specific performance requirements
- Your logging standards
- Your error handling patterns

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Built upon the foundation of github/awesome-copilot
  • Inspired by the C# and .NET developer community
  • Thanks to all contributors who help improve C# development with AI assistance

Happy Coding with GitHub Copilot and C#! πŸš€

About

A specialized collection of GitHub Copilot customizations focused on C# and .NET development.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published