Csharpのロゴ

Csharp

コミュニティ
alpham8
csharp

C#コードの作成時に使用します。C# 12/13の最新機能、レコード、パターンマッチング、null許容参照型、LINQ、async/await、コレクション、ジェネリック、sealedクラス、requiredプロパティ、ファイルスコープの名前空間に対応します。.csファイル、.csproj、C#のクラス、インターフェース、レコードが登場したときに有効になります。

Add to TypingMind

概要

公開者alpham8
リポジトリagentic-webdev
スキル名csharp
スター
4
フォーク
0
同梱ファイル
指示のみ
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    alpham8がGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Csharp」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/alpham8/agentic-webdev/tree/master/skills/csharp
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/alpham8/agentic-webdev.git /tmp/agentic-webdev
mkdir -p .claude/skills
cp -r /tmp/agentic-webdev/skills/csharp .claude/skills/csharp
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでCsharpを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にCsharpを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Csharpは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

C#

Related Skills

NeedSkill
ASP.NET Core framework (DI, middleware, APIs, EF Core)aspnet-core
TypeScript (frontend, similar type system concepts)typescript

Overview

C# is a strongly-typed, object-oriented language running on .NET. Current version: C# 13 (.NET 9).

Key principles: Nullable reference types enabled, sealed by default for services, records for DTOs, async all the way, explicit types over var.


Modern C# Features

File-Scoped Namespaces (C# 10)

csharp
// One line instead of wrapping the entire file
namespace App.Services;

public sealed class OrderService : IOrderService
{
    // ...
}

Records (C# 9+)

csharp
// Immutable data transfer objects
public sealed record UserDto(string Id, string DisplayName, string? AvatarUrl);

// Record with additional logic
public sealed record Money(decimal Amount, string Currency)
{
    public Money Add(Money other)
    {
        if (Currency != other.Currency)
        {
            throw new InvalidOperationException("Currency mismatch");
        }
        return this with { Amount = Amount + other.Amount };
    }
}

// Record struct (value type, no heap allocation)
public readonly record struct Coordinate(double Lat, double Lng);

// Positional record with extra properties
public sealed record DetectedFace(float X, float Y, float Width, float Height)
{
    public float Area => Width * Height;
}

Required Properties (C# 11)

csharp
public sealed class CreatePostRequest
{
    public required string Content { get; init; }
    public required string NetworkSlug { get; init; }
    public List<string>? MediaIds { get; init; }
}

Nullable Reference Types

csharp
// Enable in .csproj: <Nullable>enable</Nullable>

public sealed class UserService
{
    // Non-nullable: compiler guarantees non-null
    private readonly ILogger<UserService> _logger;

    // Nullable: explicitly optional
    public async Task<UserDto?> FindByEmailAsync(string email)
    {
        ApplicationUser? user = await _context.Users
            .FirstOrDefaultAsync(u => u.Email == email);

        if (user is null)
        {
            return null;
        }

        return MapToDto(user);
    }
}

Pattern Matching

csharp
// Type patterns
public string Describe(object value) => value switch
{
    int i when i > 0 => $"Positive: {i}",
    int i => $"Non-positive: {i}",
    string s => $"String: {s}",
    null => "null",
    _ => $"Unknown: {value.GetType().Name}",
};

// Property patterns
public decimal CalculateDiscount(Order order) => order switch
{
    { Total: > 1000, IsPremium: true } => order.Total * 0.2m,
    { Total: > 500 } => order.Total * 0.1m,
    { IsPremium: true } => order.Total * 0.05m,
    _ => 0m,
};

// List patterns (C# 11)
int[] numbers = [1, 2, 3, 4, 5];
bool isValid = numbers is [1, 2, ..]; // starts with 1, 2

// Relational patterns
string GetCategory(int score) => score switch
{
    >= 90 => "Excellent",
    >= 70 => "Good",
    >= 50 => "Average",
    _ => "Below average",
};

Primary Constructors (C# 12)

csharp
// Classes with primary constructor (DI-friendly)
public sealed class ChatService(
    ActionBuddiesDbContext context,
    ILogger<ChatService> logger,
    ICacheService cache) : IChatService
{
    public async Task<ChatResponse> CreateDirectChatAsync(string userId, string participantId)
    {
        logger.LogInformation("Creating chat between {UserId} and {ParticipantId}", userId, participantId);
        // context, logger, cache available as fields
    }
}

Collection Expressions (C# 12)

csharp
// Spread and initialize
List<string> combined = [..existing, "new item", ..more];
int[] numbers = [1, 2, 3, 4, 5];
ReadOnlySpan<byte> buffer = [0x00, 0xFF];

Raw String Literals (C# 11)

csharp
string json = """
    {
        "name": "ActionBuddies",
        "version": "1.0"
    }
    """;

// Interpolated raw strings
string query = $"""
    SELECT * FROM users
    WHERE email = '{email}'
    AND active = true
    """;

Sealed Classes

csharp
// Sealed prevents inheritance -- use for services, handlers, DTOs
public sealed class NotificationService : INotificationService
{
    // Cannot be subclassed -- explicit design intent
}

Target-Typed New

csharp
List<UserDto> users = new();
Dictionary<string, int> counts = new();
CancellationTokenSource cts = new(TimeSpan.FromSeconds(30));

Type System

Value Types vs Reference Types

csharp
// Value types (stack-allocated)
int count = 0;
decimal price = 9.99m;
bool active = true;
DateTime now = DateTime.UtcNow;
Guid id = Guid.NewGuid();
Status status = Status.Active;    // enum
Coordinate point = new(48.1, 11.5); // record struct

// Reference types (heap-allocated)
string name = "Alice";
List<int> numbers = [1, 2, 3];
UserDto? user = null;

Enums

csharp
public enum ModerationAction
{
    Warn,
    Suspend7Days,
    Suspend30Days,
    Ban,
    Escalate,
}

// String backing (for JSON serialization)
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum NotificationType
{
    Like,
    Comment,
    Follow,
    Mention,
    EventInvite,
}

Interfaces

csharp
public interface IChatService
{
    Task<ChatResponse> CreateDirectChatAsync(string currentUserId, string participantUserId);
    Task<List<ChatMessageDto>> GetMessagesAsync(string chatId, string userId, int page, int pageSize);
    Task<ChatMessageDto> SendMessageAsync(string chatId, string senderId, string content);
    Task DeleteMessageAsync(string chatId, string messageId, string userId);
}

Generics

csharp
public interface IRepository<T> where T : class
{
    Task<T?> FindByIdAsync(int id);
    Task<List<T>> FindAllAsync(CancellationToken ct = default);
    Task AddAsync(T entity, CancellationToken ct = default);
}

// Generic constraints
public sealed class CachedService<TKey, TValue>(ICacheService cache)
    where TKey : notnull
    where TValue : class
{
    public async Task<TValue?> GetOrSetAsync(TKey key, Func<Task<TValue>> factory, TimeSpan ttl)
    {
        string cacheKey = $"{typeof(TValue).Name}:{key}";
        TValue? cached = await cache.GetAsync<TValue>(cacheKey);

        if (cached is not null)
        {
            return cached;
        }

        TValue value = await factory();
        await cache.SetAsync(cacheKey, value, ttl);
        return value;
    }
}

LINQ

csharp
// Query syntax (less common in modern C#)
var result = from u in users
             where u.IsActive
             orderby u.Name
             select new UserDto(u.Id, u.Name, u.AvatarUrl);

// Method syntax (preferred)
List<UserDto> activeUsers = await context.Users
    .Where(u => u.IsActive)
    .OrderBy(u => u.DisplayName)
    .Select(u => new UserDto(u.Id, u.DisplayName, u.AvatarUrl))
    .ToListAsync();

// Common operators
int count = items.Count(i => i.IsValid);
UserDto? first = items.FirstOrDefault(i => i.Id == targetId);
bool any = items.Any(i => i.Score > 90);
bool all = items.All(i => i.Score >= 0);
decimal avg = items.Average(i => i.Price);
decimal sum = items.Sum(i => i.Amount);
List<string> distinct = items.Select(i => i.Category).Distinct().ToList();

// Grouping
Dictionary<string, List<Post>> byNetwork = posts
    .GroupBy(p => p.NetworkSlug)
    .ToDictionary(g => g.Key, g => g.ToList());

// Projection with index
List<(int Index, string Name)> indexed = items
    .Select((item, index) => (index, item.Name))
    .ToList();

Async / Await

csharp
// Async all the way -- never .Result or .Wait()
public async Task<PostDto> CreatePostAsync(CreatePostRequest request, string userId)
{
    Post post = new()
    {
        Content = request.Content,
        AuthorId = userId,
        CreatedAt = DateTime.UtcNow,
    };

    context.Posts.Add(post);
    await context.SaveChangesAsync();

    return MapToDto(post);
}

// Parallel async
public async Task<SearchResult> SearchAsync(string query)
{
    Task<List<UserDto>> usersTask = SearchUsersAsync(query);
    Task<List<PostDto>> postsTask = SearchPostsAsync(query);
    Task<List<SpotDto>> spotsTask = SearchSpotsAsync(query);
    Task<List<EventDto>> eventsTask = SearchEventsAsync(query);

    await Task.WhenAll(usersTask, postsTask, spotsTask, eventsTask);

    return new SearchResult
    {
        Users = usersTask.Result,
        Posts = postsTask.Result,
        Spots = spotsTask.Result,
        Events = eventsTask.Result,
    };
}

// CancellationToken propagation
public async Task<List<PostDto>> GetFeedAsync(string userId, int page, CancellationToken ct)
{
    return await context.Posts
        .Where(p => p.NetworkSlug == networkSlug)
        .OrderByDescending(p => p.CreatedAt)
        .Skip((page - 1) * 20)
        .Take(20)
        .Select(p => MapToDto(p))
        .ToListAsync(ct);
}

Collections

csharp
// Immutable collections
IReadOnlyList<string> names = ["Alice", "Bob"];
IReadOnlyDictionary<string, int> scores = new Dictionary<string, int>
{
    ["Alice"] = 95,
    ["Bob"] = 87,
};

// Frozen collections (.NET 8+ -- optimized for read-heavy)
FrozenDictionary<string, Sport> sportsLookup = sports.ToFrozenDictionary(s => s.Slug);

// Array slicing
int[] arr = [1, 2, 3, 4, 5];
int[] slice = arr[1..3];      // [2, 3]
int last = arr[^1];           // 5
int[] lastTwo = arr[^2..];    // [4, 5]

String Handling

csharp
// Interpolation
string msg = $"User {user.DisplayName} (ID: {user.Id}) logged in";

// Verbatim + interpolation
string path = $@"C:\Users\{username}\Documents";

// String.Join, Split
string csv = string.Join(", ", items.Select(i => i.Name));
string[] parts = input.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);

// StringBuilder for loops
StringBuilder sb = new();
foreach (string item in items)
{
    sb.AppendLine(item);
}

// Span-based (zero allocation)
ReadOnlySpan<char> span = input.AsSpan();
bool startsWith = span.StartsWith("prefix");

Error Handling

csharp
// Specific exceptions
public sealed class PostNotFoundException : Exception
{
    public PostNotFoundException(string postId)
        : base($"Post with ID '{postId}' was not found") { }
}

// Guard clauses with ArgumentException helpers (.NET 8+)
public void SetName(string name)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(name);
    ArgumentOutOfRangeException.ThrowIfGreaterThan(name.Length, 100);
    _name = name;
}

// Try pattern (no exceptions for expected failures)
public bool TryGetUser(string id, out UserDto? user)
{
    user = _cache.Get<UserDto>(id);
    return user is not null;
}

Common Gotchas

  1. var hides types -- Use explicit types for clarity, especially in service code. var is acceptable for new() and LINQ where the type is obvious.
  2. Async void -- Never use async void except in event handlers. Always return Task or Task<T>.
  3. .Result / .Wait() deadlocks -- Never block on async code. Use await all the way up.
  4. string.IsNullOrEmpty vs IsNullOrWhiteSpace -- Prefer IsNullOrWhiteSpace to also catch " ".
  5. DateTime.Now vs DateTime.UtcNow -- Always use UtcNow for storage and comparison. Convert to local only for display.
  6. EF Core tracking -- Use .AsNoTracking() for read-only queries to avoid memory and performance overhead.
  7. IEnumerable multiple enumeration -- Materialize with .ToList() if you iterate more than once.
  8. Sealed classes -- Seal service implementations. Unsealed classes have virtual dispatch overhead and invite uncontrolled inheritance.
  9. Dispose pattern -- IDisposable / IAsyncDisposable resources need using statements or DI lifetime management.
  10. ConfigureAwait(false) -- Not needed in ASP.NET Core (no SynchronizationContext). Required in library code targeting multiple platforms.
  11. Nullable warnings -- Never suppress with ! without justification. Use is not null checks or ?? instead.
  12. Mutable records -- Records with { get; set; } lose immutability benefits. Use { get; init; } or positional records.

Documentation References

よくある質問

AIスキル「Csharp」では何ができますか?

C#コードの作成時に使用します。C# 12/13の最新機能、レコード、パターンマッチング、null許容参照型、LINQ、async/await、コレクション、ジェネリック、sealedクラス、requiredプロパティ、ファイルスコープの名前空間に対応します。.csファイル、.csproj、C#のクラス、インターフェース、レコードが登場したときに有効になります。

TypingMindでCsharpを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Csharpはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにCsharpをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/alpham8/agentic-webdev/tree/master/skills/csharpを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Csharpを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Csharpで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもCsharpを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Csharp」は無料ですか?

alpham8がGitHubで公開しています。ライセンス条件はリポジトリでご確認ください。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇