I would like to convert this method
public static List<T> GetAllEnumValues<T>() where T : Enum
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
into a extension.
So that i can use it like this
Countries.GetAllEnumValues();
instead of this
GenericMethods.GetAllEnumValues<Countries>()
Is there a way to create an extension without passing an instance of the type to be extended?
I'd imagine something like this...
public static List<T> GetAllEnumValues<this T>() where T : Enum //not compiling for obvious reasons
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
No.
But you can import static members:
using static GenericMethods;
GetAllEnumValues<Countries>();
Also you can do it globally. For example in some other file like GlobalImports.cs
:
global using static SomeNamespace.GenericMethods;
Or via .csproj:
<ItemGroup>
<Using Include="SomeNamespace.GenericMethods" Static="True"/>
</ItemGroup>