К основному содержанию
правило официальный · GitHub

csharp — правило для GitHub Copilot: что делает и как установить

Правило задаёт Copilot стиль C#-кода: именование, nullable-типы, форматирование и работу с ASP.NET Core. Пригодится, если агент пишет по-разному в каждом файле.

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/csharp.instructions.md
Открыть на GitHub

Что делает csharp

Это файл инструкций, который Copilot подхватывает для всех файлов **/*.cs. Внутри — набор требований: PascalCase для методов и публичных членов, camelCase для приватных полей, префикс I у интерфейсов, is null вместо == null, файловые namespace и однострочные using.

Дальше правило разбирает более крупные темы: слой доступа к данным на Entity Framework Core, аутентификация через JWT Bearer и Microsoft Entra ID, валидация с data annotations и FluentValidation, версионирование API и Swagger/OpenAPI, структурированное логирование, тесты и контейнеризация через dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer.

Файл кладут в .github/instructions/csharp.instructions.md. Учтите: правило требует C# 14 и ASP.NET Core 10, поэтому на старом таргете часть советов агента придётся отбрасывать вручную. Стиль форматирования берётся из .editorconfig — если его в проекте нет, договорённости будут разъезжаться.

Какие задачи решает

  • привести именование классов и методов к одному стилю
  • убрать проверки == null в пользу is null
  • настроить слой доступа к данным на EF Core
  • добавить JWT-аутентификацию в ASP.NET Core API
  • собрать контейнер без ручного Dockerfile

Примеры запросов агенту

  • Добавь новый эндпоинт в контроллер и оформи его по правилам csharp
  • Перепиши этот сервис: nullable-типы, is null, файловые namespace
  • Покажи, как залогировать запрос через Serilog с correlation ID

Как установить csharp

Вручную: положить файлы

.github/instructions/csharp.instructions.md

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Из того же набора674

Весь набор →
dataverse-python-real-world-usecases Правило с шаблонами миграции и очистки данных Dataverse на Python: Copilot подсказывает готовые паттерны вместо общих советов. ★ 40 418звёзд репо dataverse-python-modules Правило подкладывает агенту карту модулей PowerPlatform.Dataverse: клиент, конфиг, ошибки, OData и SQL. Пригодится, когда код на Python работает с Dataverse. ★ 40 418звёзд репо dataverse-python-best-practices Правило для GitHub Copilot с рабочими шаблонами работы с Dataverse SDK для Python: авторизация, клиент, CRUD-операции. ★ 40 418звёзд репо dataverse-python-agentic-workflows Правило для GitHub Copilot с концепциями агентных сценариев на Dataverse SDK для Python: автономные агенты, MCP, A2A и проверка качества данных. ★ 40 418звёзд репо copilot-thought-logging Правило заставляет Copilot вести файл Copilot-Processing.md с планом и отметками о выполнении, чтобы вы видели ход работы и могли его поправить. ★ 40 418звёзд репо copilot-sdk-java Правило подсказывает Copilot, как писать Java-приложения на GitHub Copilot SDK: инициализация клиента, сессии, асинхронные вызовы. ★ 40 418звёзд репо convert-jpa-to-spring-data-cosmos Пошаговое правило для Copilot: переводит Spring Boot проект с JPA на Azure Cosmos DB через Spring Data Cosmos. Пригодится, когда миграция уже решена и нужен план. ★ 40 418звёзд репо context-engineering Правило для GitHub Copilot: как раскладывать файлы, типы и комментарии, чтобы подсказки попадали в проект, а не в пустоту. ★ 40 418звёзд репо

Похожие

migrate-dotnet9-to-dotnet10 dotnet Ведёт проект с net9.0 на net10.0: правит TargetFramework, чинит ошибки сборки и разбирает ломающие изменения .NET 10, C# 14, ASP.NET Core 10 и EF Core 10. CX Codex +1 3 400установок migrate-dotnet8-to-dotnet9 dotnet Скилл ведёт проект с net8.0 на net9.0: правит TargetFramework, разбирает ошибки сборки и поведенческие изменения .NET 9, C# 13, ASP.NET Core 9 и EF Core 9. CX Codex +1 3 400установок csharp-developer https://github.com/Jeffallan Настраивает правила разработки на .NET 8 и C# 12 для создания API, Blazor-приложений и работы с EF Core. Пригодится при проектировании сервисов с CQRS и Result pattern. CX Codex +1 4 800установок dotnet-architect rmyndharis Скилл для ИИ-агента, который помогает проектировать и ревьюить бэкенд на C# и ASP.NET Core. Пригодится, когда нужен разбор архитектуры или оптимизация запросов. CX Codex +1 351установок modern-csharp codewithmukesh Подсказывает агенту синтаксис C# 14: первичные конструкторы, коллекционные выражения, ключевое слово field, блоки расширений. Пригодится, когда пишете новый код на C# или чистите старый. CX Codex +1 2 900установок modern-csharp-coding-standards Aaronontheweb Задаёт правила современного C# 12+: неизменяемые рекорды, pattern matching, структуры Span<T> и асинхронный код без лишних аллокаций памяти. CX Codex +1 2 200установок

Рядом в теме «Языки программирования»

Все правила IDE по теме «Языки программирования» →

Вопросы о csharp

Как установить csharp в GitHub Copilot?

Создайте файл .github/instructions/csharp.instructions.md в репозитории и вставьте в него содержимое правила. Copilot применит его к файлам, подходящим под applyTo.

Что делает правило csharp?

Задаёт Copilot соглашения по C#: именование, форматирование, nullable-типы, работу с EF Core, аутентификацию, валидацию, логирование и тесты.

На какой версии C# и ASP.NET работает правило?

Инструкции написаны под C# 14 и ASP.NET Core 10. На более старых версиях часть советов агента не подойдёт.

Исходный текст

csharp.instructions.md · MIT
---
description: 'Guidelines for building C# applications'
applyTo: '**/*.cs'
---

# C# Development

## C# Instructions
- Always use the latest version C#, currently C# 14 features.
- Write clear and concise comments for each function.

## General Instructions
- Make only high confidence suggestions when reviewing code changes.
- Write code with good maintainability practices, including comments on why certain design decisions were made.
- Handle edge cases and write clear exception handling.
- For libraries or external dependencies, mention their usage and purpose in comments.

## Naming Conventions

- Follow PascalCase for component names, method names, and public members.
- Use camelCase for private fields and local variables.
- Prefix interface names with "I" (e.g., IUserService).

## Formatting

- Apply code-formatting style defined in `.editorconfig`.
- Prefer file-scoped namespace declarations and single-line using directives.
- Insert a newline before the opening curly brace of any code block (e.g., after `if`, `for`, `while`, `foreach`, `using`, `try`, etc.).
- Ensure that the final return statement of a method is on its own line.
- Use pattern matching and switch expressions wherever possible.
- Use `nameof` instead of string literals when referring to member names.
- Ensure that XML doc comments are created for any public APIs. When applicable, include `<example>` and `<code>` documentation in the comments.

## Project Setup and Structure

- Guide users through creating a new .NET project with the appropriate templates.
- Explain the purpose of each generated file and folder to build understanding of the project structure.
- Demonstrate how to organize code using feature folders or domain-driven design principles.
- Show proper separation of concerns with models, services, and data access layers.
- Explain the Program.cs and configuration system in ASP.NET Core 10 including environment-specific settings.

## Nullable Reference Types

- Declare variables non-nullable, and check for `null` at entry points.
- Always use `is null` or `is not null` instead of `== null` or `!= null`.
- Trust the C# null annotations and don't add null checks when the type system says a value cannot be null.

## Data Access Patterns

- Guide the implementation of a data access layer using Entity Framework Core.
- Explain different options (SQL Server, SQLite, In-Memory) for development and production.
- Demonstrate repository pattern implementation and when it's beneficial.
- Show how to implement database migrations and data seeding.
- Explain efficient query patterns to avoid common performance issues.

## Authentication and Authorization

- Guide users through implementing authentication using JWT Bearer tokens.
- Explain OAuth 2.0 and OpenID Connect concepts as they relate to ASP.NET Core.
- Show how to implement role-based and policy-based authorization.
- Demonstrate integration with Microsoft Entra ID (formerly Azure AD).
- Explain how to secure both controller-based and Minimal APIs consistently.

## Validation and Error Handling

- Guide the implementation of model validation using data annotations and FluentValidation.
- Explain the validation pipeline and how to customize validation responses.
- Demonstrate a global exception handling strategy using middleware.
- Show how to create consistent error responses across the API.
- Explain problem details (RFC 9457) implementation for standardized error responses.

## API Versioning and Documentation

- Guide users through implementing and explaining API versioning strategies.
- Demonstrate Swagger/OpenAPI implementation with proper documentation.
- Show how to document endpoints, parameters, responses, and authentication.
- Explain versioning in both controller-based and Minimal APIs.
- Guide users on creating meaningful API documentation that helps consumers.

## Logging and Monitoring

- Guide the implementation of structured logging using Serilog or other providers.
- Explain the logging levels and when to use each.
- Demonstrate integration with Application Insights for telemetry collection.
- Show how to implement custom telemetry and correlation IDs for request tracking.
- Explain how to monitor API performance, errors, and usage patterns.

## Testing

- Always include test cases for critical paths of the application.
- Guide users through creating unit tests.
- Do not emit "Act", "Arrange" or "Assert" comments.
- Copy existing style in nearby files for test method names and capitalization.
- Explain integration testing approaches for API endpoints.
- Demonstrate how to mock dependencies for effective testing.
- Show how to test authentication and authorization logic.
- Explain test-driven development principles as applied to API development.

## Performance Optimization

- Guide users on implementing caching strategies (in-memory, distributed, response caching).
- Explain asynchronous programming patterns and why they matter for API performance.
- Demonstrate pagination, filtering, and sorting for large data sets.
- Show how to implement compression and other performance optimizations.
- Explain how to measure and benchmark API performance.

## Deployment and DevOps

- Guide users through containerizing their API using .NET's built-in container support (`dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer`).
- Explain the differences between manual Dockerfile creation and .NET's container publishing features.
- Explain CI/CD pipelines for NET applications.
- Demonstrate deployment to Azure App Service, Azure Container Apps, or other hosting options.
- Show how to implement health checks and readiness probes.
- Explain environment-specific configurations for different deployment stages.

© github · MIT · github/awesome-copilot

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой