ardalis / ardalis/SmartEnum

SmartEnum<TEnum>.List does not work if fields are not defined on TEnum

Open
#349 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
2.4k
Forks
184
PR merge metrics
No merged PRs in 30d

Description

The usual usage of `SmartEnum` is like this I believe:

```csharp
public class Foo : SmartEnum { }
```

For some rather esoteric reasons, I'm trying to use it like this:

```csharp
public class Foo
{
public class Bar: SmartEnum { }
}
```

Note that the class deriving from `SmartEnum` is different than the type `TEnum` in `SmartEnum` (`Bar` vs. `Foo`). Is this a supported scenario?

The reason I'm trying to make the second option work is to avoid a naming collision. My class (`Foo` in the example) has a property with the same name as one of the enumerated options that I want to expose as a static field. Obviously the names collide. One idea to avoid the name collision was to introduce a nested class that defines the enumeration options. In other words, usage would like this:

```csharp
var someValue = Foo.Bar.SomeValue;
```

...rather than the more usual:

```csharp
var someValue = Foo.SomeValue;
```

I've found that the `SmartEnum.List` property doesn't work in this scenario. `List` is ultimately populated with a call to `GetAllOptions()`, which is defined like this:

```csharp
private static TEnum[] GetAllOptions()
{
Type baseType = typeof(TEnum);

return Assembly.GetAssembly(baseType)
.GetTypes()
.Where(t => baseType.IsAssignableFrom(t))
.SelectMany(t => t.GetFieldsOfType())
.OrderBy(t => t.Name)
.ToArray();
}
```

I wonder, would it be possible to change this implementation in a backwards compatible manner such that the "normal" scenario would continue to work as before, while also supporting my "new" scenario?

Contributor guide

Open the contributing guide

Research direction

Start by locating SmartEnum.List and the GetAllOptions() implementation shown in the issue. Add coverage for both the usual self-referencing enum and a nested Bar deriving from SmartEnum, then verify that List discovers the expected options in both cases without breaking existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
backend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.