There are some recent updates to C# that mean you can use Enum as a generic type constraint, and I'm trying to leverage this new feature to make some extension methods that will work on all enums.
Something like this:
public static class EnumToSequenceExtension
{
public static IEnumerable<T> ToSequence<T>(this T e)
where T : Enum
{
foreach (T value in Enum.GetValues(e.GetType()))
{
yield return value;
}
}
}
What follows is how I'd like to use this method, which doesn't compile as it stands right now, it's an attempt to describe in pseudo-code what I'm trying to achieve;
IEnumerable<TestEnum> sequence = TestEnum.ToSequence();
Where TestEnum is an enum type I have, e.g.
public enum TestEnum { Hello, World }
I'm looking for some simple working code that is something very simple to use with a "fluent" feel to it, by which I mean it "reads well".
No, you cannot do that, not as long as TestEnum is an enum type, as you cannot extend these with members.
Since TestEnum is not an instance, and you can only create extension methods for instances, not for types, you cannot get TestEnum.ToSequence() to compile.
So the best you can get is to call the method manually, and not as an extension method.
Now, as @Bagdan Gilevich mentions in his comment, this should compile:
TestEnum.SomeEnumItem.ToSequence()
I'll leave opinions aside, you will have to make up your own mind if this is acceptable.
There is also a language feature suggestion for C# 8 (or later), called Extension Everything. This may give you what you want but we'll have to see what happens with it.
Lasse Vågsæther Karlsen's answer is correct. Another alternative is simply using a static class with a static method and passing a generic parameter. C# 7.3+
public static class EnumHelpers
{
public static IEnumerable<TEnum> Sequence<TEnum>() where TEnum: struct, Enum
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
}
}
usage:
EnumHelpers.Sequence<SomeEnum>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With