How would the GetAll() function be used in a real example?
⚠Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
I usually make two other methods that use GetAll() to convert from string/int to the object itself.
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
return fields.Select(field => field.GetValue(null)).Cast<T>();
}
public static T FromString<T>(string name) where T : Enumeration
{
return GetAll<T>().Single(r => String.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase));
}
public static T FromValue<T>(int value) where T : Enumeration
{
return GetAll<T>().Single(r => r.Value.Equals(value));
}
I usually use those methods to convert data coming from a request or from the database itself, like the example below (configuring a type in EF Core):
private void MapConversions(object sender, EntityTypeBuilder<Instrucao> builder)
{
builder.Property(x => x.Tipo)
.HasConversion(tipoInstrucao => tipoInstrucao.ToString(), stringInstrucao => Enumeration.FromString<TipoInstrucao>(stringInstrucao));
}
Reference: Ardalis: enum alternatives
Hi @wdicks, thanks for your feedback!
That sample you mention looks like a nice one for real applications.
The other one I've encountered several times is something like getting all possible values a status can have, to display user friendly names, or to build a select input with them.
In the case of eShopOnContainers it's used in the following code, for database seeding:
Where GetPredefinedCardTypes() is the following code in the same file:
private IEnumerable<CardType> GetPredefinedCardTypes()
{
return Enumeration.GetAll<CardType>();
}
Hope this helps.
Closing this issue.
Most helpful comment
Hi @wdicks, thanks for your feedback!
That sample you mention looks like a nice one for real applications.
The other one I've encountered several times is something like getting all possible values a status can have, to display user friendly names, or to build a select input with them.
In the case of eShopOnContainers it's used in the following code, for database seeding:
https://github.com/dotnet-architecture/eShopOnContainers/blob/43fe719e98bb7e004c697d5724a975f5ecb2191b/src/Services/Ordering/Ordering.API/Infrastructure/OrderingContextSeed.cs#L42-L44
Where GetPredefinedCardTypes() is the following code in the same file:
Hope this helps.