Source profileQuality 95/100

Metalnib/dotnet-episteme-skills/skills/dotnet-techne-csharp-type-design-performance/SKILL.md

dotnet-techne-csharp-type-design-performance

Use when designing types and collections for hot paths and low-allocation .NET code. Keywords: readonly struct, sealed class, ValueTask, Span, FrozenDictionary, FrozenSet, allocation optimisation.

Source repository stars
12
Declared platforms
0
Static risk flags
0
Last source update
2026-08-20
Source checked
2026-08-25

Decision brief

What it does: where it fits

NET code. Keywords: readonly struct, sealed class, ValueTask, Span, FrozenDictionary, FrozenSet, allocation optimisation.

Best for

  • Designing new types and APIs
  • Reviewing code for performance issues
  • Choosing between class, struct, and record

Not for

  • Tasks that require unconfirmed production actions or broad system permissions.
  • Environments where the pinned source and install steps cannot be inspected.

Compatibility matrix

Platform support, with evidence labels

PlatformStatusEvidenceWhat to check
CodexNot declaredNo explicit evidencePortability before use
Claude CodeNot declaredNo explicit evidencePortability before use
CursorNot declaredNo explicit evidencePortability before use
Gemini CLINot declaredNo explicit evidencePortability before use
Open the compatibility checker

Installation

Inspect first. Install second.

The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

Source-detected install commandSource
npx skills add https://github.com/Metalnib/dotnet-episteme-skills --skill "skills/dotnet-techne-csharp-type-design-performance"
Safe inspection promptEditorial

Inspect the Agent Skill "dotnet-techne-csharp-type-design-performance" from https://github.com/Metalnib/dotnet-episteme-skills/blob/d169327d980a07c207b935215342071941c00ff6/skills/dotnet-techne-csharp-type-design-performance/SKILL.md at commit d169327d980a07c207b935215342071941c00ff6. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

Workflow

What the source asks the agent to do

  1. 01

    When to Use This Skill

    Use this skill when: - Designing new types and APIs - Reviewing code for performance issues - Choosing between class, struct, and record - Working with collections and enumerables

    Designing new types and APIsReviewing code for performance issuesChoosing between class, struct, and record
  2. 02

    Core Principles

    1. Seal your types - Unless explicitly designed for inheritance 2. Prefer readonly structs - For small, immutable value types 3. Prefer static pure functions - Better performance and testability 4. Defer enumeration - Don't materialize until you need to 5. Return immutable colle…

    Seal your types - Unless explicitly designed for inheritancePrefer readonly structs - For small, immutable value typesPrefer static pure functions - Better performance and testability
  3. 03

    Seal Classes by Default

    Sealing classes enables JIT devirtualization and communicates API intent.

    JIT can devirtualize method callsCommunicates "this is not an extension point"Prevents accidental breaking changes
  4. 04

    Readonly Structs for Value Types

    Structs should be readonly when immutable. This prevents defensive copies.

    Structs should be readonly when immutable. This prevents defensive copies.
  5. 05

    When to Use Structs

    Review the “When to Use Structs” section in the pinned source before continuing.

    Review and apply the “When to Use Structs” source section.

Permission review

Static risk signals and limitations

No configured static risk pattern was detected

This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

Evidence record

Why each signal appears

EvidenceSourceComputedTestedEditorial
SignalValueEvidence typeMeaning
Quality score95/100ComputedDocumentation, specificity, maintenance, and trust rules
Repository stars12SourceRepository attention, not individual Skill quality
Compatibility0 platformsSourceDeclared in the catalog source record
Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

Pinned source

Provenance and original SKILL.md

Repository
Metalnib/dotnet-episteme-skills
Skill path
skills/dotnet-techne-csharp-type-design-performance/SKILL.md
Commit
d169327d980a07c207b935215342071941c00ff6
License
MIT
Collected
2026-08-25
Default branch
main
View the original SKILL.md

Type Design for Performance

When to Use This Skill

Use this skill when:

  • Designing new types and APIs
  • Reviewing code for performance issues
  • Choosing between class, struct, and record
  • Working with collections and enumerables

Core Principles

  1. Seal your types - Unless explicitly designed for inheritance
  2. Prefer readonly structs - For small, immutable value types
  3. Prefer static pure functions - Better performance and testability
  4. Defer enumeration - Don't materialize until you need to
  5. Return immutable collections - From API boundaries

Seal Classes by Default

Sealing classes enables JIT devirtualization and communicates API intent.

// DO: Seal classes not designed for inheritance
public sealed class OrderProcessor
{
    public void Process(Order order) { }
}

// DO: Seal records (they're classes)
public sealed record OrderCreated(OrderId Id, CustomerId CustomerId);

// DON'T: Leave unsealed without reason
public class OrderProcessor  // Can be subclassed - intentional?
{
    public virtual void Process(Order order) { }  // Virtual = slower
}

Benefits:

  • JIT can devirtualize method calls
  • Communicates "this is not an extension point"
  • Prevents accidental breaking changes

Readonly Structs for Value Types

Structs should be readonly when immutable. This prevents defensive copies.

// DO: Readonly struct for immutable value types
public readonly record struct OrderId(Guid Value)
{
    public static OrderId New() => new(Guid.NewGuid());
    public override string ToString() => Value.ToString();
}

// DO: Readonly struct for small, short-lived data
public readonly struct Money
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }
}

// DON'T: Mutable struct (causes defensive copies)
public struct Point  // Not readonly!
{
    public int X { get; set; }  // Mutable!
    public int Y { get; set; }
}

When to Use Structs

Use Struct WhenUse Class When
Small (≤16 bytes typically)Larger objects
Short-livedLong-lived
Frequently allocatedShared references needed
Value semantics requiredIdentity semantics required
ImmutableMutable state

Prefer Static Pure Functions

Static methods with no side effects are faster and more testable.

// DO: Static pure function
public static class OrderCalculator
{
    public static Money CalculateTotal(IReadOnlyList<OrderItem> items)
    {
        var total = items.Sum(i => i.Price * i.Quantity);
        return new Money(total, "USD");
    }
}

// Usage - predictable, testable
var total = OrderCalculator.CalculateTotal(items);

Benefits:

  • No vtable lookup (faster)
  • No hidden state
  • Easier to test (pure input → output)
  • Thread-safe by design
  • Forces explicit dependencies
// DON'T: Instance method hiding dependencies
public class OrderCalculator
{
    private readonly ITaxService _taxService;  // Hidden dependency
    private readonly IDiscountService _discountService;  // Hidden dependency

    public Money CalculateTotal(IReadOnlyList<OrderItem> items)
    {
        // What does this actually depend on?
    }
}

// BETTER: Explicit dependencies via parameters
public static class OrderCalculator
{
    public static Money CalculateTotal(
        IReadOnlyList<OrderItem> items,
        decimal taxRate,
        decimal discountPercent)
    {
        // All inputs visible
    }
}

Don't go overboard - Use instance methods when you genuinely need state or polymorphism.


Defer Enumeration

Don't materialize enumerables until necessary. Avoid excessive LINQ chains.

// BAD: Premature materialization
public IReadOnlyList<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .ToList()  // Materialized!
        .OrderBy(o => o.CreatedAt)  // Another iteration
        .ToList();  // Materialized again!
}

// GOOD: Defer until the end
public IReadOnlyList<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .OrderBy(o => o.CreatedAt)
        .ToList();  // Single materialization
}

// GOOD: Return IEnumerable if caller might not need all items
public IEnumerable<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .OrderBy(o => o.CreatedAt);
    // Caller decides when to materialize
}

Async Enumeration

Be careful with async and IEnumerable:

// BAD: Async in LINQ - hidden allocations
var results = orders
    .Select(async o => await ProcessOrderAsync(o))  // Task per item!
    .ToList();
await Task.WhenAll(results);

// GOOD: Use IAsyncEnumerable for streaming
public async IAsyncEnumerable<OrderResult> ProcessOrdersAsync(
    IEnumerable<Order> orders,
    [EnumeratorCancellation] CancellationToken ct = default)
{
    foreach (var order in orders)
    {
        ct.ThrowIfCancellationRequested();
        yield return await ProcessOrderAsync(order, ct);
    }
}

// GOOD: Batch processing for parallelism
var results = await Task.WhenAll(
    orders.Select(o => ProcessOrderAsync(o)));

ValueTask vs Task

Use ValueTask for hot paths that often complete synchronously. For real I/O, just use Task.

// DO: ValueTask for cached/synchronous paths
public ValueTask<User?> GetUserAsync(UserId id)
{
    if (_cache.TryGetValue(id, out var user))
    {
        return ValueTask.FromResult<User?>(user);  // No allocation
    }

    return new ValueTask<User?>(FetchUserAsync(id));
}

// DO: Task for real I/O (simpler, no footguns)
public Task<Order> CreateOrderAsync(CreateOrderCommand cmd)
{
    // This always hits the database
    return _repository.CreateAsync(cmd);
}

ValueTask rules:

  • Never await a ValueTask more than once
  • Never use .Result or .GetAwaiter().GetResult() before completion
  • If in doubt, use Task

Span and Memory for Bytes

Use Span<T> and Memory<T> instead of byte[] for low-level operations.

// DO: Accept Span for synchronous operations
public static int ParseInt(ReadOnlySpan<char> text)
{
    return int.Parse(text);
}

// DO: Accept Memory for async operations
public async Task WriteAsync(ReadOnlyMemory<byte> data)
{
    await _stream.WriteAsync(data);
}

// DON'T: Force array allocation
public static int ParseInt(string text)  // String allocated
{
    return int.Parse(text);
}

Common Span Patterns

// Slice without allocation
ReadOnlySpan<char> span = "Hello, World!".AsSpan();
var hello = span[..5];  // No allocation

// Stack allocation for small buffers
Span<byte> buffer = stackalloc byte[256];

// Use ArrayPool for larger buffers
var buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
    // Use buffer...
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer);
}

Collection Return Types

Return Immutable Collections from APIs

// DO: Return immutable collection
public IReadOnlyList<Order> GetOrders()
{
    return _orders.ToList();  // Caller can't modify internal state
}

// DO: Use frozen collections for static data (.NET 8+)
private static readonly FrozenDictionary<string, Handler> _handlers =
    new Dictionary<string, Handler>
    {
        ["create"] = new CreateHandler(),
        ["update"] = new UpdateHandler(),
    }.ToFrozenDictionary();

// DON'T: Return mutable collection
public List<Order> GetOrders()
{
    return _orders;  // Caller can modify!
}

Internal Mutation is Fine

public IReadOnlyList<OrderItem> BuildOrderItems(Cart cart)
{
    var items = new List<OrderItem>();  // Mutable internally

    foreach (var cartItem in cart.Items)
    {
        items.Add(CreateOrderItem(cartItem));
    }

    return items;  // Return as IReadOnlyList
}

Collection Guidelines

ScenarioReturn Type
API boundaryIReadOnlyList<T>, IReadOnlyCollection<T>
Static lookup dataFrozenDictionary<K,V>, FrozenSet<T>
Internal buildingList<T>, then return as readonly
Single item or noneT? (nullable)
Zero or more, lazyIEnumerable<T>

Frozen Collections Guidance (.NET 8+)

Use FrozenDictionary<TKey,TValue> and FrozenSet<T> for read-mostly lookup data that is built once and queried many times.

using System.Collections.Frozen;

private static readonly FrozenDictionary<string, Handler> Handlers =
    new Dictionary<string, Handler>
    {
        ["create"] = new CreateHandler(),
        ["update"] = new UpdateHandler()
    }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);

private static readonly FrozenSet<string> ReservedWords =
    new[] { "if", "else", "for", "while" }.ToFrozenSet(StringComparer.Ordinal);

About "Frozen list"

.NET does not provide FrozenList<T>. For list-like read-mostly data, use:

  • ImmutableArray<T> when you need value-like immutability semantics
  • plain array (T[]) for minimal overhead and fast iteration
  • combine with FrozenDictionary/FrozenSet when you also need lookup acceleration
using System.Collections.Immutable;

private static readonly ImmutableArray<string> OrderedSteps =
    ["Parse", "Validate", "Transform", "Persist"];

private static readonly string[] OrderedStepsFast =
    { "Parse", "Validate", "Transform", "Persist" };

Quick Reference

PatternBenefit
sealed classDevirtualization, clear API
readonly record structNo defensive copies, value semantics
Static pure functionsNo vtable, testable, thread-safe
Defer .ToList()Single materialization
ValueTask for hot pathsAvoid Task allocation
Span<T> for bytesStack allocation, no copying
IReadOnlyList<T> returnImmutable API contract
FrozenDictionaryFastest lookup for static data

Anti-Patterns

// DON'T: Unsealed class without reason
public class OrderService { }  // Seal it!

// DON'T: Mutable struct
public struct Point { public int X; public int Y; }  // Make readonly

// DON'T: Instance method that could be static
public int Add(int a, int b) => a + b;  // Make static

// DON'T: Multiple ToList() calls
items.Where(...).ToList().OrderBy(...).ToList();  // One ToList at end

// DON'T: Return List<T> from public API
public List<Order> GetOrders();  // Return IReadOnlyList<T>

// DON'T: ValueTask for always-async operations
public ValueTask<Order> CreateOrderAsync();  // Just use Task

Resources

Frequently asked questions

What to verify before installation and use

What does the dotnet-techne-csharp-type-design-performance source document cover?

NET code. Keywords: readonly struct, sealed class, ValueTask, Span, FrozenDictionary, FrozenSet, allocation optimisation.

How do I install dotnet-techne-csharp-type-design-performance?

The source record exposes this install command: npx skills add https://github.com/Metalnib/dotnet-episteme-skills --skill "skills/dotnet-techne-csharp-type-design-performance". Inspect the command and pinned source before running it.

Alternatives

Compare before choosing

Computed 10045,511

coreyhaines31/marketingskills

ab-testing

When the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this," "which version is better," "test two versions," "statistical significance," "how long should I run this test," "growth experiments," "experiment velocity," "experiment backlog," "ICE score," "experimentation program

Computed 100147

oaustegard/claude-skills

featuring

Generate hierarchical _FEATURES.md files that describe what a codebase DOES from a user/consumer perspective, anchored to source symbols via tree-sitting. Supports large complex codebases through feature-driven decomposition into sub-feature files. Uses a multi-pass synthesis: orientation → detail → overview rewrite. Use when someone says "what does this do", "document features", "feature inventory", "_FEATURES.md", or needs to understand a codebase's purpose before modifying it. Complements tre

Computed 1008

narrative-io/narrative-skills-marketplace

design-analysis

Translate a fuzzy analytical question into a rigorous investigation plan. Interrogates the ask, grounds the plan in the available data dictionary, applies analytical best practices, and produces a structured brief of query specifications for a downstream query-writing skill. Plans, does not write SQL. Use when: "why did X drop", "is there a relationship between A and B", "who are our highest-value customers", "what's driving the change in Y", "investigate this trend", "design an analysis for", "

Computed 1007

event4u-app/agent-config

existing-ui-audit

Use BEFORE writing or editing any non-trivial UI — inventories components, design tokens, shadcn primitives, and reusable patterns into state.ui_audit. Hard gate for the ui directive set.