SmartEnum.GetEnumerator FieldNotImplementException
LorneCash opened this issue · 1 comments
Given these enums I would like to be able to do the following but I can't:
var eventTypesCluster2 = SmartEnum.GetEnumerator<EventType>().Where(x => x.GetValueOf<Cluster>("Cluster") == Cluster.Two).ToList();
The goal here as you can see is to get a subset of valid enum values for a given situation but if just one enum value does not have the EnumValue with the specified key the whole enumeration fails??? That makes no sense!
I can demonstrate that issue more clearly like this:
var test = EventType.Status.GetValueOf<Cluster>("Cluster");
My expectation would be that this should return null
since the EnumValue doesn't exist.
but I could kinda understand your apprehension there since it doesn't really make sense for non-nullable types like enum Cluster
in this case.
A possible solution would be to keep allowing GetValueOf<>
to throw the FieldNotImplementException
for non-nullable types but to return null for nullable types. With that solution by adding the ?
now any variable can be nullable and would return null rather than the FieldNotImplementException
:
var test = EventType.Status.GetValueOf<Cluster?>("Cluster");
If you're not so keen on my previous suggestion hopefully you'll like this potential solution because it should feel familiar. Make a TryGetValueOf<>
method.
An example might look like this:
var test = EventType.Status.TryGetValueOf<Cluster>("Cluster", out var clusterValue);
In my opinion I would say you should strongly consider implementing both options because being able to enumerate the enum without throwing an exception should be valuable in many cases.
public enum Cluster
{
Unknown = -1,
Zero = 0,
One = 1,
Two = 2
}
public enum EventType
{
[EnumValue("Code", "T")]
[EnumValue("Cluster", Cluster.One)]
Trade,
[EnumValue("Code", "Q")]
[EnumValue("Cluster", Cluster.One)]
Quote,
[EnumValue("Code", "A")]
[EnumValue("Cluster", Cluster.Two)]
AggregatePerSecond,
[EnumValue("Code", "AM")]
[EnumValue("Cluster", Cluster.Two)]
AggregatePerMinute,
[EnumValue("Code", "I")]
[EnumValue("Cluster", Cluster.Two)]
Imbalance,
[EnumValue("Code", "Status")]
Status,
}
I also tried adding this EnumValueAttribute
to Status [EnumValue("Cluster", null)]
and then doing this: var test = EventType.Status.GetValueOf<Cluster?>("Cluster");
but then I just get a different exception: SmartEnums.WrongEnumValueTypeException
My goal here is that I'm REALLY trying NOT to add an additional value to enum Cluster
just to handle when the EventType does not have a cluster.