Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a extension for a typeparameter?

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();
}
like image 939
HWS-SLS Avatar asked Aug 20 '26 22:08

HWS-SLS


1 Answers

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>
like image 148
Guru Stron Avatar answered Aug 22 '26 12:08

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!