Files
Examples/GerstITS.Examples.Api/Common/Configurations/Extensions/IConfigurationExtensions.cs
2023-12-18 12:10:34 +01:00

28 lines
890 B
C#

using System;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace GerstITS.Examples.Api.Configurations;
public static class IConfigurationExtensions
{
#region Methods
public static TEnum GetFlaggedEnum<TEnum>(this IConfiguration configuration, string key)
where TEnum : struct, IConvertible
{
ThrowsAnExceptionIfTypeIsNotAnEnumeration<TEnum>();
return (TEnum)(object)(configuration.GetSection(key)?
.Get<TEnum[]>() ?? Enumerable.Empty<TEnum>())
.Sum(i => (int)(object)i);
}
private static void ThrowsAnExceptionIfTypeIsNotAnEnumeration<TEnum>() where TEnum : struct, IConvertible
{
if (!typeof(TEnum).IsEnum)
throw new InvalidOperationException($"{typeof(TEnum)} is not supported.");
}
#endregion
}