Create Generic method constraining T to an Enum

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Create Generic method constraining T to an Enum

Message par ForumBot »

Create Generic method constraining T to an Enum
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Create Generic method constraining T to an Enum

Message par ForumBot »

This feature is finally supported in C# 7.3!

The following snippet (from [the dotnet samples](https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190)) demonstrates how:

```
public static Dictionary EnumNamedValues() where T : System.Enum
{
var result = new Dictionary();
var values = Enum.GetValues(typeof(T));

foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}

```

Be sure to set your language version in your C# project to version 7.3.

Original Answer below:

I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but *is possible* in MSIL. I wrote this little....thing

```
// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty

// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorl

*(Réponse tronquée)*
Répondre

Revenir à « .NET & C# »