Skip to content

Feature/482 enum guard is defined - #1210

Open
szv wants to merge 2 commits into
CommunityToolkit:mainfrom
szv:feature/482-enum-guard-is-defined
Open

Feature/482 enum guard is defined#1210
szv wants to merge 2 commits into
CommunityToolkit:mainfrom
szv:feature/482-enum-guard-is-defined

Conversation

@szv

@szv szv commented Aug 16, 2026

Copy link
Copy Markdown

Closes #482

PR Summary

Adds Guard.IsDefined to validate that an enum value corresponds to a declared member.

  • Introduces a generic enum guard with caller argument expression support.
  • Caches enum values in a FrozenSet to avoid repeated reflection and provide fast lookups.
  • Adds a dedicated throw helper with a descriptive ArgumentException.
  • Supports .NET Standard targets through the required collections package.
  • Adds unit tests covering cache initialization, valid values, and undefined values.
  • Exposes internals to the diagnostics test project for direct cache validation.

Alternative Approach

An alternative would be an enum source generator that detects enum types used with Guard.IsDefined and generates specialized membership checks, such as switch-based implementations. The generated code could avoid the runtime Enum.GetValues initialization, frozen-set allocation, hashing, and the internal use of Enum.IsDefined, potentially improving startup and lookup performance.

PR Checklist

  • Created a feature/dev branch in your fork (vs. submitting directly from a commit on main)
  • Based off latest main branch of toolkit
  • PR doesn't include merge commits (always rebase on top of our main, if needed)
  • Tested code with current supported SDKs
  • New component Guard method
  • Tests for the changes have been added (for bug fixes / features) (if applicable)
  • Header has been added to all new source files (run build/UpdateHeaders.bat)
  • Contains NO breaking changes
  • Every new API (including internal ones) has full XML docs
  • Code follows all style conventions

Sebastian Szvetecz added 2 commits August 16, 2026 12:42
Introduce Guard.IsDefined<TEnum> for efficient enum value checks using cached sets. Add EnumCache<TEnum> and ThrowHelper for fast lookups and detailed exceptions. Update csproj to refine package references and add System.Collections.Immutable for .NET Standard.
Added Test_Guard.Enum.cs. Updated AssemblyInfo.cs with InternalsVisibleTo for unit tests. Introduced Test_Guard.Enum.cs with unit tests for EnumCache and Guard.IsDefined, including a new file-scoped TestEnum.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: Guard.IsDefined<TEnum>()

1 participant