|
| 1 | +# Issues found in src/Thinktecture.Runtime.Extensions.SourceGenerator/Extensions/EnumExtensions.cs |
| 2 | + |
| 3 | +## Errors |
| 4 | + |
| 5 | +1) Invalid array cast for underlying values |
| 6 | +- Code: `public static readonly int[] Values = (int[])Enum.GetValues(typeof(T));` |
| 7 | +- Problem: `Enum.GetValues(typeof(T))` returns an array of the enum type (`T[]`), not an array of the underlying numeric type. Casting `T[]` to `int[]` always fails at runtime with InvalidCastException, regardless of the enum’s underlying type. |
| 8 | +- Impact: Any first access to `EnumHelper<T>` (e.g., calling `GetValidValue`) will throw. |
| 9 | +- Fix options: |
| 10 | + - Use `Enum.GetValuesAsUnderlyingType(typeof(T))` (returns an `Array` of the actual underlying numeric type), and adjust comparison logic accordingly. |
| 11 | + - If the API is intended to support only int-based enums, guard explicitly: |
| 12 | + ``` |
| 13 | + if (Enum.GetUnderlyingType(typeof(T)) != typeof(int)) throw new NotSupportedException(...); |
| 14 | + ``` |
| 15 | + and remove the invalid cast. |
| 16 | +
|
| 17 | +2) `GetValidValue<T>(this int value)` incompatible with non-int underlying enums |
| 18 | +- Code: `public static T? GetValidValue<T>(this int value) where T : struct, Enum` |
| 19 | +- Problems: |
| 20 | + - The parameter is `int`, but enums may use any integral underlying type (`sbyte, byte, short, ushort, int, uint, long, ulong`). For non-int underlying enums this can truncate or mis-compare values. |
| 21 | + - Combined with the broken `Values` array cast, the method is currently non-functional. |
| 22 | +- Impact: Incorrect behavior or exceptions for enums not using `int` as underlying type. |
| 23 | +- Fix options: |
| 24 | + - Generalize input type by comparing via `Convert.ToUInt64(value)` against enum values converted to `UInt64`, or |
| 25 | + - Use `Enum.GetValuesAsUnderlyingType` and compare using typed values, or |
| 26 | + - Restrict to int-based enums with a runtime check and document the limitation. |
| 27 | +
|
| 28 | +## Warnings |
| 29 | +
|
| 30 | +1) `IsValid<T>` does not account for [Flags] combinations |
| 31 | +- Code: `Array.IndexOf(EnumHelper<T>.Items, item) >= 0` |
| 32 | +- Problem: Returns `false` for valid bitwise combinations unless explicitly declared as named members. |
| 33 | +- Risk: Surprising semantics for flags enums; may be intended, but if general validity for flags is desired, this is too strict. |
| 34 | +- Suggestion: If flags support is needed, validate via bitwise decomposition against defined values or document current behavior clearly. |
| 35 | +
|
| 36 | +2) Redundant generic constraints |
| 37 | +- Code: `where T : struct, Enum` (in `GetValidValue`) |
| 38 | +- Problem: `Enum` constraint implies value type; adding `struct` is redundant. |
| 39 | +- Suggestion: Simplify to `where T : Enum` for consistency with `IsValid<T>`. |
0 commit comments